simpleXMLElement attributes and foreach

2020-05-06 10:43发布

问题:

If I run in the debugger, the program performs just 2 iterations correctly, and then do an infinite loop. If I exchange the line with foreach, it works correctly. Why?

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:

$xml = simplexml_load_file('test.xml');
$rows = $xml->xpath('reports/get/row');
foreach($rows as $row){
        $item = [];
        $attr = $row->attributes();
        print_r($attr);
        $i = 0;
        foreach($attr as $key => $value){
        //foreach($row->attributes() as $key => $value){               
               $item[$key] = (string) $value;
               $i++;
        }
    $arr[] = $item;
}
return $arr;