【问题标题】:Converting XML to JSON using PHP while preserving Arrays使用 PHP 将 XML 转换为 JSON,同时保留数组
【发布时间】:2011-11-03 02:54:40
【问题描述】:

我需要将 XML 文档转换为 JSON,以便轻松访问 JavaScript 中的数据。我目前正在使用这种方法将 XML 转换为 JSON:

json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

但是,当一个元素仅包含 1 个子元素时,我遇到了问题。使用 SimpleXML 解析时,它被视为对象而不是数组。我希望它们始终被视为数组,除非元素仅包含文本。

例子:

$xml = <<<END
<xml>
  <TESTS>
    <TEST>TEXT HERE</TEST>
  </TESTS>
</xml>
END;

echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

这个输出:

{"TESTS":{"TEST":"TEXT HERE"}}

如果我在 下添加另一个元素,那么输出就是我想要的:

$xml = <<<END
<xml>
  <TESTS>
    <TEST>TEXT HERE</TEST>
    <TEST>MORE TEXT HERE</TEST>
  </TESTS>
</xml>
END;

echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

输出:

{"TESTS":{"TEST":["TEXT HERE","TEXT HERE"]}}

注意元素是如何包含在 JSON 数组而不是 JSON 对象中的。有没有办法强制将元素解析为数组?

【问题讨论】:

  • 看来你还是有对象但是这个元素的值在第一种情况下是字符串但在第二种情况下是数组。
  • 我认为您必须遍历 XML 并手动转换为数组。即使有一种方法可以强制使用数组而不是对象,第一个示例也会以 JSON 格式结束:{"Tests":[{"Test":["Text HERE"]}]}。我想这不是你真正想要的。
  • 你传入了一个(simplexml 类的)对象...当然你会从 json_encode 中得到一个对象。
  • @Marc B 我认为 OP 正在寻找与 JSON_FORCE_OBJECT 选项类似的数组
  • 看来您的第二个示例 - SimpleXMLElement 退回到表示 节点的数组 - 只是因为别无选择。在同一个对象中不能有两个名为 TEST 的属性。所以 SimpleXML 使用数组作为一种绝望的行为。有了一个项目,就不会发生这种情况。因此,正如其他评论者已经说过的那样,您可能必须自己挑选 XML。

标签: php xml json simplexml


【解决方案1】:

我不得不处理同样的情况。这是该问题的第一个快速解决方案 - 适用于您的示例。

class JsonWithArrays
{
    protected $root, $callback;

    public function __construct( SimpleXMLElement $root )
    {
        $this->root = $root;
    }

    /**
     * Set a callback to return if a node should be represented as an array
     * under any circumstances.
     *
     * The callback receives two parameters to react to: the SimpleXMLNode in
     * question, and the nesting level of that node.
     */
    public function use_callback_forcing_array ( $callback )
    {
        $this->callback = $callback;
        return $this;
    }

    public function to_json ()
    {
        $transformed = $this->transform_subnodes( $this->root, new stdClass(), 0 );
        return json_encode( $transformed );
    }

    protected function transform_subnodes ( SimpleXMLElement $parent, stdClass $transformed_parent, $nesting_level )
    {
        $nesting_level++;

        foreach( $parent->children() as $node )
        {
            $name = $node->getName();
            $value = (string) $node;

            if ( count( $node->children() ) > 0 )
            {
                $transformed_parent->$name = new stdClass();
                $this->transform_subnodes( $node, $transformed_parent->$name, $nesting_level );
            }
            elseif ( count( $parent->$name ) > 1 or $this->force_array( $node, $nesting_level ) )
            {
                $transformed_parent->{$name}[] = $value;
            }
            else
            {
                $transformed_parent->$name = $value;
            }
        }

        return $transformed_parent;
    }

    protected function force_array ( $node, $nesting_level )
    {
        if ( is_callable( $this->callback ) )
        {
            return call_user_func( $this->callback, $node, $nesting_level );
        }
        else
        {
            return false;
        }
    }
}

$xml = <<<END
<xml> 
  <TESTS> 
    <TEST>TEXT HERE</TEST> 
  </TESTS> 
</xml> 
END;

$xml2 = <<<END
<xml> 
  <TESTS> 
    <TEST>TEXT HERE</TEST> 
    <TEST>MORE TEXT HERE</TEST> 
  </TESTS> 
</xml> 
END;

// Callback using the node name. Could just as well be done using the nesting
// level.
function cb_testnode_as_array( SimpleXMLElement $node, $nesting_level )
{
    return $node->getName() == 'TEST';
}

$transform = new JsonWithArrays( new SimpleXMLElement($xml, LIBXML_NOCDATA) );
echo $transform
    ->use_callback_forcing_array( 'cb_testnode_as_array' )
    ->to_json();

echo PHP_EOL;

$transform2 = new JsonWithArrays( new SimpleXMLElement($xml2, LIBXML_NOCDATA) );
echo $transform2
    ->use_callback_forcing_array( 'cb_testnode_as_array' )
    ->to_json();

【讨论】:

    【解决方案2】:
    echo json_encode(json_decode(json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA)), true));
    

    这确实很愚蠢,但你首先如果全部转换为对象,然后在数组中解码并转换为类似数组样式的 json..))

    【讨论】:

    • 试过了,没用。就像 OP 发布的代码一样返回 {"TESTS":{"TEST":"TEXT HERE"}}。
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2012-02-02
    • 1970-01-01
    相关资源
    最近更新 更多