【问题标题】:Split XML nodes into php array将 XML 节点拆分为 php 数组
【发布时间】:2014-03-12 13:08:55
【问题描述】:

我正在尝试拆分 XML 字符串,如下所示:

<root>
  <item attr='test'>test1</item>
  <anotherItem>test2</anotherItem>
  <item3><t>Title</t><foo></foo></item3>
</root>

我希望数组看起来像:

$arrXml[0] = "<item attr='test'>test1</item>";
$arrXml[1] = "<anotherItem>test2</anotherItem>";
$arrXml[2] = "<item3><t>Title</t><foo></foo></item3>";

我已经查看了Split XML in PHP 中的解决方案,但它们仅适用于只有“项目”节点的 XML 文档。

我尝试过使用 XmlReader,但在使用 read() 之后,如何获取当前节点,包括它自己的带有属性的 xml? readOuterXml() 似乎不起作用,只输出内部值。

xml 不包含\n,所以我不能使用explode()。

【问题讨论】:

    标签: php xml split


    【解决方案1】:

    使用 SimpleXML:

    $root = simplexml_load_string($xml);
    $arrXml = array();
    
    foreach($root as $child)
        $arrXml[] = $child->asXml();
    

    【讨论】:

    • 当我运行这段代码时:"1232" 我得到这个:["123","2"],所以没有第一个 ?
    • @Anorionil 当您在浏览器中输出 xml 时,不要忘记 htmlspecialchars,因为 xml 节点将被视为 HTML 代码...
    • 啊,谢谢!它一直在工作,我只是没看到:/ Dumb :(
    【解决方案2】:

    根据您想要的输出,您尝试做的是解析字符串而不是 XML 字符串。 你可以使用正则表达式或者干脆直接爆炸。

    类似:

    $lines = explode("\n", $string);
    $arrXml = array();
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line == '<root>' || $line == '</root>') {
            continue;
        }
        $arrXml[] = $line;
    }
    

    【讨论】:

    • 恐怕不同的行之间没有 \n 。我添加了换行符只是为了让我的示例更具可读性。
    • 比你应该在你的问题中提到的 :)
    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多