Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.