【问题标题】:read xml node's attribute using php使用php读取xml节点的属性
【发布时间】:2012-09-09 16:02:12
【问题描述】:

我正在尝试从该文件中读取 xml 节点的属性 使用简单的 xml 阅读器

<songs>
<song title="On Mercury" artist="Red Hot Chili Peppers" path="/red-hot-chili-peppers/on-mercury.mp3" />
<song title="Universally Speaking" artist="Red Hot Chili Peppers" path="/red-hot-chili-peppers/universally-speaking.mp3" />
</songs>

我用那个代码来阅读它 但它给了我 xml 解析错误

<?php
$xml = simplexml_load_file("playlist.xml") 
       or die("Error: Cannot create object");

foreach($xml->children() as $data){
      echo $data->song['title'];
      echo "<br />";

}

?>

请帮帮我

【问题讨论】:

    标签: php xml xml-parsing simplexml


    【解决方案1】:

    您无需同时调用-&gt;children()-&gt;song。第一个为您提供特定节点的所有子节点,而不考虑标签名称,第二个为您提供标签名称为“song”的特定节点的所有子节点。

    试试:

    foreach($xml->song as $song){
        echo $song['title'];
        echo "<br />";
    }
    

    相当于:

    foreach($xml->children() as $data) {
        if ( $data->getName() == 'song' ) {
            echo $data['title'];
            echo "<br />";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 1970-01-01
      相关资源
      最近更新 更多