I’m trying to iterate through a Twitter XML File, where the container tag is <users>, and each user is <user>. I need to create a variable $id based on the XML attribute <id> for each user.
Username is already instantiated.
$url = "http://api.twitter.com/1/statuses/friends/$username.xml";
$xmlpure = file_get_contents($url);
$listxml = simplexml_load_string($xmlpure);
foreach($listxml->users->children() as $child)
{
$id = $child->{"id"};
//Do another action
}
But I’m getting this error:
Warning: main() [function.main]: Node no longer exists in /home/…/bonus.php on line 32
Line 32 is the foreach statement, and I don’t actually USE the main() method.
It might be that the node represented by
$childdoes not have an<id/>child. You can check that out using isset() or even by outputing the node’s XML withecho $child->asXML();Also, if you intent to use
$idas a string, you should cast it as such.Another thing, you could load the document like this:
Finally, when asking a question here, please always link to a relevant sample of the original XML document.
Update
As suspected, you just don’t access the right nodes. If you specify the name of an inexistent node (“users” in your example) SimpleXML creates some kind of a temporary phantom node instead of generating an error. This is to allow creating new nodes more easily I believe.
Anyway, here’s what your script should look like:
Always name your PHP vars according to the node they represent so that you always know where you are in the tree; it will save you a lot of future similar troubles. The root node is
<users/>therefore the variable is$usersand same for<user/>/$user.