SimpleXMLelement中foreach循环的问题

I'm trying to teach myself to handle the SimpleXMP_read_file command / object.

So I have looked deeply into the problem at "simpleXMLElement attributes and foreach" ( simpleXMLElement attributes and foreach ).

copied it bit by bit into my PHP browser and ran it.

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>

modified the php like this: 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>') ;
        }
}

I get no errors but only 2 lines :

test
test

No data.

Can anyone tell me why ?

You are doing a foreach over $row->attributes(). Therefore each iteration of the loop is a different attribute. None of the attributes have a $key['a'] value set.

You probably want to do:

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

after doing a print_r($rows); i have got the following. Now you can access the array elements and class objects directly by $row->attributes['a'] etc.

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

Output:

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

Now you can access like $fo['a'] etc...