duanjizi9443 2012-08-28 07:31
浏览 5
已采纳

foreach和simplexml

It's my xml file:

<?xml version="1.0" encoding="utf-8" ?> 
<documentElement>
    <rows>
        <row>
            <column>1</column>
            <column>David</column>
            <column>Johnson</column>
        </row>
        <row>
            <column>2</column>
            <column>Jack</column>
            <column>Nixon</column>
        </row>
    </rows>
</documentElement>

I want to loop over rows and add them to an array. I passed it to simplexml and then loop through these objects, but couldn't do it:

$xml->rows
$xml->rows->row
$xml->row
$xml->column

What should I do?

Thanks.

  • 写回答

5条回答 默认 最新

  • dtmsaqtly798322992 2012-08-28 07:42
    关注

    This is actually one of the more basic examples:

    $sxml = simplexml_load_string($xml);
    
    foreach($sxml->rows->row as $name => $row)
    {
        echo $name, ': ', var_dump($row);
    }
    

    Which will give you the following output:

    row: object(SimpleXMLElement)#3 (1) {
      ["column"]=>
      array(3) {
        [0]=>
        string(1) "1"
        [1]=>
        string(5) "David"
        [2]=>
        string(7) "Johnson"
      }
    }
    row: object(SimpleXMLElement)#5 (1) {
      ["column"]=>
      array(3) {
        [0]=>
        string(1) "2"
        [1]=>
        string(4) "Jack"
        [2]=>
        string(5) "Nixon"
      }
    

    You can find an online-demo here: http://codepad.org/CYyQhvnM

    You should actually take a look at the simple exmamples section in the manual, it has some very insightful examples that are explained more in depth than mine here:

    I hope the answer is helpful anyway. Related questions are:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)