开发者

navigating through this xml structure with php

开发者 https://www.devze.com 2022-12-11 06:42 出处:网络
Im trying to loop through and display info from the following xml structure. <users_list> −<users type=\"array\">

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


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";


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

  • http://nl2.php.net/manual/en/function.simplexml-load-string.php
  • http://nl2.php.net/manual/en/class.simplexmlelement.php


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消