Good day. I understand simplexml, and faced the following problem. Suppose there is an xml file of the following content (a_xml.xml):

<?xml version="1.0" encoding="utf-8"?> <stat> <user> <cart>13</cart> <subid>2</subid> </user> <user> <cart>54</cart> <subid>-</subid> </user> </stat> 

And there is the same simple php code:

 <? $xml = simplexml_load_file('a_xml.xml'); foreach($xml->stat->user as $user) { echo $user->cart; } ?> 

And at this moment I expect to see the numbers 13 and 54 on the screen. But in fact it turns out: " Warning: Invalid argument supplied for foreach () ". Why it happens? Where is the mistake?

And the strangest thing for me is that if you make a small change in the xml file, namely put the <stat> tag inside the <rss> , that is:

 <?xml version="1.0" encoding="utf-8"?> <rss> <stat> <user> <cart>13</cart> <subid>2</subid> </user> <user> <cart>54</cart> <subid>-</subid> </user> </stat> </rss> 

So everything works fine, the desired result appears on the screen. But naturally, I am not satisfied with such a way out of the problem. What to do?

    2 answers 2

    • The XML standard implies the presence of a single root- element. In the first case, stat plays its role, in the second, rss . The simplexml_load_file method returns an object that is just the root- element.

    • Therefore, when you make $xml = simplexml_load_file , then $xml is essentially a representation of your $stat , which means that $xml->stat is an empty collection of elements.

    To solve the problem in the first case (without an additional level of nesting rss ) it is enough to use foreach($xml->user as $user)

    • Thank you very much, it works. - Stifax
    • @ Kotik_hochet_kukat, the first, basic element (stat) can be completely omitted, because the XML parser is smart enough to find the root of the DOM-model of the XML document. - Free_man

    You can use the usual FOR-loop based on this:

     echo $xml->user[0]->cart; //13 echo $xml->user[1]->cart; //54