加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 当我使用它时,为什么SimpleXML会将我的数组更改为数组的

发布时间:2020-12-13 13:32:04 所属栏目:PHP教程 来源:网络整理
导读:这是我的代码: $string = XML?xml version='1.0'? test testing lolhello/lol lolthere/lol /testing/testXML;$xml = simplexml_load_string($string);echo "All of the XML:n";print_r $xml;echo "nnJust the 'lol' array:";print_r $xml-testing-lol;
这是我的代码:
$string = <<<XML
<?xml version='1.0'?> 
<test>
 <testing>
  <lol>hello</lol>
  <lol>there</lol>
 </testing>
</test>
XML;
$xml = simplexml_load_string($string);
echo "All of the XML:n";
print_r $xml;
echo "nnJust the 'lol' array:";
print_r $xml->testing->lol;

输出:

All of the XML:

SimpleXMLElement Object
(
    [testing] => SimpleXMLElement Object
        (
            [lol] => Array
                (
                    [0] => hello
                    [1] => there
                )

        )

)




Just the 'lol' array:

SimpleXMLElement Object
(
    [0] => hello
)

为什么它只输出[0]而不是整个数组?我不懂.

这是因为你有两个lol元素.要访问第二个,您需要这样做:
$xml->testing->lol[1];

这会给你“那里”

$xml->testing->lol[0];

会给你“你好”

SimpleXMLElement的children()方法将为您提供一个包含元素的所有子元素的对象,例如:

$xml->testing->children();

将为您提供一个包含“测试”SimpleXMLElement的所有子项的对象.

如果需要迭代,可以使用以下代码:

foreach($xml->testing->children() as $ele)
{
    var_dump($ele);
}

这里有关于SimpleXMLElement的更多信息:

http://www.php.net/manual/en/class.simplexmlelement.php

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读