views:

134

answers:

1

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.

What am I doing wrong?

A: 

It might be that the node represented by $child does not have an <id/> child. You can check that out using isset() or even by outputing the node's XML with echo $child->asXML();

Also, if you intent to use $id as a string, you should cast it as such.

$id = (string) $child->id;

Another thing, you could load the document like this:

$listxml = simplexml_load_file($url);

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:

$users = simplexml_load_file($url);

foreach ($users->user as $user)
{
    $id = (string) $user->id;
}

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 $users and same for <user/>/$user.

Josh Davis
Sorry about that.Here is a sample XML file: http://api.twitter.com/1/statuses/friends/randomuser.xmlIs there a difference between the $child->id syntax and the $child->{"id"} syntax?
phpeffedup
No, there's no functional difference between the two syntaxes, which is why I prefer the simpler one ;)
Josh Davis