将 simple_html_dom 变量放入数组中
我正在尝试使用 simple_html_dom 从网站中提取一些信息。
目前我正在使用:
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;
}
}
效果很好。但是我需要能够回显 foreach 循环之外的每个变量。如果我使用上面的代码执行此操作,则只会显示最终结果,即在我尝试提取的 10 个产品中,仅显示第 10 个。
有没有一种方法可以使用数组来存储每个 foreach 循环的所有结果,然后在整个循环完成后将它们回显出来?
像这样的事情:
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);
抱歉,如果这个问题令人困惑,我对 PHP 没有最好的掌握,尤其是数组!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对标题和价格数据也执行相同的操作。
Do the same for the title and price data as well.
不确定我是否完全理解你的问题,请尝试以下操作。
等等...
Not sure if I completely understand you question, try the following.
And so on...