Jump to content

XML looping


Vince889

Recommended Posts

Take a look here:

http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=YahooDemo&query=test

 

That is a generated XML file from Yahoo's API. If you take a look, it has a node titled "Question". With PHP, how can I loop through each "Question" node and grab all of it's children as well?

 

I tried this code, but apparently it did not work:

 

$req = "http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=YahooDemo&query=php";
$res = file_get_contents($req);
$xml = simplexml_load_string($res);

foreach ($xml->xpath('//Question') as $question) { // "//question" means for each question node
  echo((string)$question['Subject']." - ".(string)$question['Content']); // you get all the child nodes in $question
} 

Link to comment
https://forums.phpfreaks.com/topic/211902-xml-looping/
Share on other sites

Not sure exactly what you're trying to do.  But if you want to loop through each question and all of its children then you can use something like:

 

ini_set ("display_errors", "1"); 
error_reporting(E_ALL);

$req = "http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=YahooDemo&query=php";
$res = file_get_contents($req);
$xml = simplexml_load_string($res);

foreach ($xml->xpath('/ResultSet/Question') as $question) 
{ // "//question" means for each question node
   foreach($question->children() as $name => $child)
   {   
      echo $name . "\n" . $child; // you get all the child nodes in $question
   }   
} 

?>

 

You may also want to write a cron job that collects the XML and stores it locally so it doesn't take as long to load the contents.

Link to comment
https://forums.phpfreaks.com/topic/211902-xml-looping/#findComment-1104486
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.