tags:

views:

71

answers:

3

Im trying to loop through and display info from the following xml structure.

<users_list>
  −<users type="array">
    +<user>
      <id>Blah</id>
    </user>
    +<user></user>
    +<user></user>
  </users>
  <next_link>6</next_link>
  <prev_link>4</prev_link>
</users_list>

Im using the following PHP to grab the nodes.

  $xml = simplexml_load_string($rawxml);
  foreach($xml->users_list AS $key){
   $name = $key->users->user->{"id"};
  }
   $next = $key->{"next_link"};
   $prev = $key->{"prev_link"};

Ive tried a couple variations, but i dont see any effect. I either get nothing when i echo my variables, or invalid arguments when on my foreach function

A: 

print_r($xml) should give you all the information you need. You will probably find that the actual array is $xml->user_list->users->user, also casting helps save some time

foreach($xml->user_list->users->user as $value) {
  $name = (string) $value->id;
}
Les
+2  A: 

When troubleshooting in PHP, var_dump and print_r are your friend!

If you wish to browse your result like an array, then cast it to an array.

$value = (array) $value;

I did the following:

$xmlStr = '<users_list>
<users type="array">
<user>
<id>Blah</id>
</user>
<user></user>
<user></user>
</users>
<next_link>6</next_link>
<prev_link>4</prev_link>
</users_list>';

$xml = simplexml_load_string($xmlStr); 

foreach($xml->users->user AS $key=>$value){
    $value = (array) $value;
    $name = $value["id"];
    var_dump($name);
}

which gives the output:

string(4) "Blah"
NULL
NULL

Check the PHP help documents for further info on simplexml

nash
Note that print_r() and var_dump() just don't work so well with SimpleXMLElement, children won't appear and some attributes won't either.
Josh Davis
+1  A: 

When using SimpleXML, you should always name your variables after the root node they contain, it makes things simpler and obvious:

$users_list = simplexml_load_string(
    '<users_list>
      <users type="array">
        <user>
          <id>Blah</id>
        </user>
        <user></user>
        <user></user>
      </users>
      <next_link>6</next_link>
      <prev_link>4</prev_link>
    </users_list>'
);

foreach ($users_list->users->user as $user)
{
    echo "User ", $user->id, "\n";
}

echo "next: ", $users_list->next_link, "\n";
echo "prev: ", $users_list->prev_link, "\n";
Josh Davis
Warning: Invalid argument supplied for foreach() in functions.php on line 55 Array -- Thats what i get when i use this method.
Patrick
The code I've published works as-is. My guess is your variable isn't named $users_list. Try `error_reporting(E_ALL);`
Josh Davis