DOM Parsing for each statement is only returning 1 result

Hello,
I was hoping someone might be able to help me out. I am using the yahoo related query search with DOM. I have similar scripts that query Yahoo with the same technique below and work just fine.

The problem I am having with this one is that the code will only echo the first result returned instead of all 10. Below is a a copy of the returned results and the actual php code I am using. Can any one spot what I have typed or done wrong and point it out for me please?

The XML is:

<query yahoo:count="10" yahoo:created="2011-01-06T11:45:49Z" yahoo:lang="en-US">
&#8722;
<results>
<Result>toy r us</Result>
<Result>toy story</Result>
<Result>toy poodle</Result>
<Result>toy stores</Result>
<Result>toy haulers</Result>
<Result>toy wiz</Result>
<Result>toy box</Result>
<Result>toy news international</Result>
<Result>toy guns</Result>
<Result>toy watch</Result>
</results>
</query>

The PHP code is:

 $q= ('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20search.suggest%20where%20query%3D%22test%22&results=10');
 
  $doc = new DOMDocument();
  $doc->load( $q );
  $domresults = $doc->getElementsByTagName( "results" );
	  foreach( $domresults as $result )
		  {
			  $results = $result->getElementsByTagName( "Result" );
			  $result = $results->item(0)->nodeValue;
			  
		    echo $result ;
		  }

Try SimpleXML. :slight_smile:


<?php
$query = new SimpleXMLElement(
  'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20search.suggest%20where%20query%3D%22test%22&results=10',
  null,
  true
);

foreach($query->results->Result as $result){
  echo (string)$result, "\
" ;
}

Or if you wanted to stick with the DOM


<?php

$doc = new DOMDocument();
$doc->load("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20search.suggest%20where%20query%3D%22test%22&results=10");

foreach($doc->getElementsByTagName("Result") as $result)
{
    echo $result->nodeValue, "\
";
}

Thanks Anthony,Salathe,

Dom and Curl have been my main methods for getting xml due to the header requirements of CJ Developer. That bit of code actually optimizes mine by five lines, which is a lot considering I call on similar functions quite often and multiple times.

2 questions

  1. What exactly are you declaring null and true after the url?

  2. Do you see anything wrong with my code? The fact it doesn’t work is still bothering me.