使用php代码从xml文件中提取数据

时间:2015-02-25 20:10:47

标签: php xml

我有一个包含如下数据的xml文件,但我正在进行测试运行以查看是否可以提取所有数据。但是我在获取imgpath值方面遇到了麻烦。

<datas>
  <projects> 
    <project>
      <projectlogopath>logo1.gif</projectlogopath>
      <groupname>group1</groupname>
      <imgtitle>Company1</imgtitle>
      <images>
        <imgpath>comp1_sc01.jpg</imgpath>
        <imgpath>comp1_sc02.jpg</imgpath>
        <imgpath>comp1_sc03.jpg</imgpath>
      </images>
    </project>
    <project>
      <projectlogopath>logo2.gif</projectlogopath>
      <groupname>group2</groupname>
      <imgtitle>Company2</imgtitle>
      <images>
        <imgpath>comp2_sc01.jpg</imgpath>
      </images>
    </project>
  </projects>
</datas>

这是我在php中写的读取xml文件

foreach($xml->children() as $projects){
    foreach($projects->children() as $project => $data){
        echo $data->projectlogopath;
        echo "<br />";
        echo $data->groupname;
        echo "<br />";
        echo $data->imgtitle;
        echo "<br />";

        foreach($data->images->children() as $data2) {
            echo $data2->imgpath;
            echo "<br />";
        }      
        echo "***<br />";
    }
}

我的结果如下所示。我做错了什么?非常感谢

logo1.gif
group1
Company1



***
logo2.gif
group2
Company2

***

1 个答案:

答案 0 :(得分:0)

我不确定您的预期结果是什么,但请尝试此更改:

foreach($data->images->children() as $imgpath=>$data2) {
            echo $data2;
            echo "<br />";
        }