When I execute this code only 2nd iteration's details are showed.
How can I iterate through both pages page 1 and page 2?
I have following code div which resides img:
$ratings = array();
for ($pageNum = 1; $pageNum < 3; $pageNum++) {
$html = file_get_contents("http://www.example.com/store/abc/page/$pageNum");
@$dom = DOMDocument::loadHTML($html);
//Init the XPath object
$xpath = new DOMXpath($dom);
//Query the DOM
$rating = $xpath->query( '//div[contains(@class, "rating fl")]//img' );
//Display the results as in the previous example
foreach ($rating as $link) {
//echo $link->getAttribute('title'),'<br>';
$ratings[] = $link->getAttribute('title');
if (sizeof($ratings) == 15) {
// var_dump($ratings);
}
}
}
You reset $ratings
on every iteration so you only have the last passes values in the $ratings
array.
Simplified version:
for($pageNum=1; $pageNum<3;$pageNum++){
$ratings = array();
$rating = array(0,1,2);
foreach($rating as $link){
$ratings[] = $pageNum;
echo $pageNum;
}
}
print_r($ratings);
Output:
111222Array
(
[0] => 2
[1] => 2
[2] => 2
)
If you comment out the ratings intializing or move it outside the loop it should work as expected.
for($pageNum=1; $pageNum<3;$pageNum++){
//$ratings = array();
$rating = array(0,1,2);
foreach($rating as $link){
$ratings[] = $pageNum;
echo $pageNum;
}
}
print_r($ratings);
Output:
111222Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 2
[5] => 2
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments