SimpleXMLelement中foreach循环的问题

时间:2015-01-07 20:30:08

标签: php

我正在尝试自学处理SimpleXMP_read_file命令/对象。

所以我在“simpleXMLElement属性和foreach”中深入研究了这个问题( simpleXMLElement attributes and foreach)。

将它一点一点地复制到我的PHP浏览器中并运行它。

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<response result="0">
    <reports>
        <get count="2">
            <row a="first" b="second" comment="test" c=""/>
            <row a="first1" b="second2" comment="test2" c=""/>
        </get>
    </reports>
</response>

像这样修改了php: PHP:

$xml = simplexml_load_file('test.xml');
$rows = $xml->xpath('reports/get/row');
foreach($rows as $row)
{

        foreach($row->attributes() as $key) 
        {               
           echo ('test: '.$key['a'] .' '.$key['b'].' '.$key['comment'].' '.$key['c'].'<br>') ;
        }
}

我没有错误但只有2行:

test
test

没有数据。

谁能告诉我为什么?

2 个答案:

答案 0 :(得分:1)

您正在foreach而不是$row->attributes()。因此,循环的每次迭代都是不同的属性。没有任何属性设置$key['a']值。

您可能想要这样做:

foreach($rows as $row){
    $key = $row->attributes();
    echo 'test: '.$key['a'] .' '.$key['b'].' '.$key['comment'].' '.$key['c'].'<br>';
}

答案 1 :(得分:0)

做完print_r($rows);之后我得到了以下内容。现在,您可以通过$row->attributes['a']等直接访问数组元素和类对象。

 foreach($rows as $row){
     $xmlObjElement = json_decode(json_encode((array)$row), TRUE);
     foreach($xmlObjElement as $fo){
        print_r( $fo );
     }
 }

<强>输出:

Array
(
    [a] => first1
    [b] => second2
    [comment] => test2
    [c] =>
)

现在您可以访问$fo['a']等...

相关问题