【问题标题】:Trying to extract more than one node from an xml file via PHP试图通过 PHP 从 xml 文件中提取多个节点
【发布时间】:2012-02-20 04:30:12
【问题描述】:

我的 XML 文件是:

<?xml version="1.0" encoding="UTF-8"?>
<item>
    <title>Hello</title>
    <link>http://www.google.com</link>
</item>
<item>
    <title>Some Title</title>
    <link>http://www.google.com</link>
</item>

我想从 xml 文件中获取这个数组:

  0 => 
    array
      'title' => string 'Hello' (length=5)
      'link' => string 'http://www.google.com' (length=21)
  1 => 
    array
      'title' => string 'Some Title' (length=10)
      'link' => string 'http://www.google.com' (length=21)

有可能吗?如果有,谁能帮帮我?

干杯!

【问题讨论】:

    标签: php xml simplexml


    【解决方案1】:

    您的 XML 格式不正确。由于标签是文档中的第一个标签,因此以下 根据规范有效地终止了文档。您想添加一个包装 的附加标签,例如.......

    要在 PHP 中简单处理,请使用 simplexml,例如:

    <?php
    
    $xml=<<<EOD
    <?xml version="1.0" encoding="UTF-8"?>
    <document>
    <item>
        <title>Hello</title>
        <link>http://www.google.com</link>
    </item>
    <item>
        <title>Some Title</title>
        <link>http://www.google.com</link>
    </item>
    </document>
    EOD;
    
    $sxml = simplexml_load_string($xml);
    var_dump($sxml);
    

    请注意,simplexml 默认返回对象而不是数组值。但是,从对象而不是数组中提取所需的值相当简单。例如:

    echo $sxml->item[0]->title;
    

    会使用上面的 XML 输出 Hello。

    【讨论】:

    • 明白了,谢谢。我遇到的唯一问题是我打算通过 PHP 将新项目附加到 xml 文件中,但现在我显然不能。你知道任何可以让我通过 PHP 向 xml 文件添加新的 节点的方法吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2020-05-05
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多