View Full Version : Looping DomDocument

03-21-2010, 10:20 PM
Hi Guys,

I'm trying to loop through the ciontents of an html page using domDocument, i can get the results back great but it only retrieves 1 result (because i'm not using a foreach)


if (isset($_GET['searchDeep']))
print $searchString;
// Deep search code
$searchString = str_replace( " ","+",$searchString);
$search_url = "http://www.site.com/mkplSearchResult.htm?dores=true&includeKeywords=$searchString&firstResult=50";

// make the cURL request to $search_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Firefox (WindowsXP) - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv: Gecko/20070725 Firefox/');
curl_setopt($ch, CURLOPT_URL,$search_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$html = curl_exec($ch);
if (!$html) {
echo "<p class=\"fcs-message-error\">cURL error:" . curl_error($ch) . " (Number " . curl_errno($ch).")</p>";

// parse the html into a DOMDocument
$dom = new DOMDocument();

$xpath = new DOMXPath($dom);
$paras = $xpath->query("//div[@id='results']//tr/td[@class='details']/h4/a");
$para = $paras->item(0);

$urlt = $para->textContent;
if($urlt == '' | $urlt == null) {
echo '<p class="fcs-message-error">No Deep search products found!</p>';

} else {

// Loop
foreach ($something as $something)

$url = $para->getAttribute('href');
$url = str_replace("zzzzz", "graham25s", $url);

$xpath = new DOMXPath($dom);
$paras = $xpath->query("//div[@id='results']//td[@class='details']//div[@class='description']");
$para = $paras->item(0);
$description = $para->textContent;

$xpath = new DOMXPath($dom);
$paras = $xpath->query("//div[@id='results']//td[@class='details']//h4/a");
$para = $paras->item(0);
$title = $para->textContent;

$link = '<a rel="nofollow" href="'.$url.'">'.$title.'</a><br />';

//print "<br/><strong>".$link."</strong><br/>".$description;
print $link;



it's the foreach part i'm having trouble with i have put one in above where i think it should go, any help would be appreciated

thanks a lot guys


03-21-2010, 11:26 PM
it's the foreach part i'm having trouble with

foreach ($something as $something)
really no idea, why that fails?

03-21-2010, 11:31 PM
Hi Mate,

I meant to to that believe it or not i was trying to show "i need something as something" its what that something is, is the problem :)



03-22-2010, 08:22 AM
let’s put it this way, if you loop over something, making the first item something, whereover do you want to loop next (you can’t loop over an item, only arrays are valid)?