Reputation: 35
I am trying to extract some info from a website using simple_html_dom.
Currently I am using:
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
echo $img;
}
foreach ($results->find('a.title') as $title) {
echo $title->plaintext;
}
foreach ($results->find('div.price') as $price) {
echo $price;
}
}
Which works fine. However I need to be able to echo each variable outside of the foreach loop. If I do that using the above code, only the final result will be displayed, i.e. out of the 10 products I am trying to extract only the 10th will be displayed.
Is there a way I can use an array to store all the results from each foreach loop then echo them out once the overall loop is finished?
Something like this:
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
array($img);
}
foreach ($results->find('a.title') as $title) {
array($title->plaintext);
}
foreach ($results->find('div.price') as $price) {
array($price);
}
}
echo array($img);
echo array($title);
echo array($price);
Sorry if this question is confusing I don't have the best grasp on PHP, especially arrays!
Upvotes: 1
Views: 799
Reputation: 31
Not sure if I completely understand you question, try the following.
$priceList = $titleList = $imgList = array();
foreach ($html->find('div.product') as $results) {<br/>
foreach ($results->find('div.image') as $img) {<br/>
$imgList[] = $img;<br/>
}<br/>
foreach ($results->find('a.title') as $title) {<br/>
titleList[] = $title;<br/>
}<br/>
foreach ($results->find('div.price') as $price) {<br/>
priceList[] = $price;<br/>
}<br/>
}<br/>
foreach ($imgList as $img) {<br/>
echo $img;<br/>
}<br/>
And so on...
Upvotes: 0
Reputation: 3600
$img = array();
$title = array();
$price = array();
foreach ($html->find('div.product') as $results) {
$img[] = $results->find('div.image');
$title[] = $results->find('a.title');
$price[] = $results->find('div.price');
}
print_r($img);
print_r($title);
print_r($price);
Upvotes: 1
Reputation: 326
$array_img = array();
$array_title = array();
$array_price = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
$array_img[] = $img;
}
foreach ($results->find('a.title') as $title) {
$array_title[]= $title->plaintext;
}
foreach ($results->find('div.price') as $price) {
$array_price[]= $price;
}
}
echo '<pre>';
print_r($array_img);
print_r($array_title);
print_r($array_price);
echo '</pre>';
Upvotes: 3
Reputation: 360572
$images = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('div.image') as $img) {
$images[] = $img; // append $img to the $images array
}
}
var_dump($images);
Do the same for the title and price data as well.
Upvotes: 1