...

View Full Version : Loop in wrong place or much more serious?



DoA
03-19-2010, 11:27 PM
Hi guys,

My script does the following:

Takes a textarea input, cleans it & splits it into an array. 1 text area line = 1 array value.
Open an HTML page with DOM and find the 'Target' on the page.
Returns it's position.

Here's what should be output:

Text Area Line 1 - Position (of Text Area Line 1)
Text Area Line 2 - Position (of Text Area Line 2)

However what's actually being output is:

Text Area Line 1 - Position (of Text Area Line 1)
Text Area Line 2 - Position (of Text Area Line 1)

Why is it holding on to the position variable? I think it's simply because my loops are in the wrong place.



<?php

// Get Textarea string and trim spaces & blank lines
$textarea = $_POST['phrase'];
$textarea = trim($textarea, " \r\n");

// Explode textarea on newlines to get individual search phrases
$textarea_array = explode("\n", $textarea);

//
//Get site to look for (Target) & force removal of http:// & http://www. to be user friendly.
// Removal is case insensitive.
//

$Target = $_POST['target'];

function remove_http($Target = '')
{
return(str_ireplace(array('http://www.','http://'), '', $Target));
}
$Target = remove_http($Target);

//
//
//Main Foreach loop - takes each line of text area and searches URL for results.
//
//

foreach ($textarea_array as $XQuery) {

//Replace space ( ) with + to ensure compatibility in the next step
$XQuery = str_replace(" ","+",$XQuery);

$html = "http://www.mysite.co.uk/search?api=" .$XQuery ."&productvalid=1";
$dom = new DOMDocument;
@$dom->loadHTMLFile($html);
$xpath = new DOMXPath($dom);
$aTag = $xpath->query('//h3[@class="r"]/a');
foreach ($aTag as $val) {
$arr[] = $val->getAttribute('href');
}

foreach($arr as $key => $value)
{
if(stristr($value, $Target))
{
//
// Result found, Position is the key + 1 (first array value is zero).
// Then further define it to include the nice text, this'll make it easier to echo later.
//
$Position = $key + 1;
// break;
}
else {
//
// Result not found, set $Position to not found.
//
$Position = "Not Found";
}
}
//
// We're out of the loop, so tell the good people the results!
//
echo $XQuery;
echo "-";
echo $Position;
}
?>

tomws
03-20-2010, 12:50 AM
It appears to be a loop problem. Here's a trimed version that may make it easier to see:

foreach ($textarea_array as $XQuery) {
foreach ($aTag as $val) {
// set $arr
}
foreach($arr as $key => $value)
}
// output
}
See, each pass of the outer foreach re-initializes the $arr, so the inner loop that's grabbing the position is finding position 1 each time.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum