foreach和simplexml [英] foreach and simplexml

查看:86
本文介绍了foreach和simplexml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的xml文件:

<?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>

我想遍历行并将它们添加到数组中.我将其传递给simplexml,然后遍历这些对象,但无法做到这一点:

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

我该怎么办?

谢谢.

推荐答案

这实际上是更基本的示例之一:

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);
}

将为您提供以下输出:

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"
  }

您可以在此处找到在线演示: http://codepad.org/CYyQhvnM

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:

这篇关于foreach和simplexml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆