当我解析一些html并获取html元素数组时,我想获取第一项。这是代码:
$url = getLink($good);
$html = file_get_html($url);
$offers = array_filter($html->find('div.b-offers'), function($node) {
return $node->class == 'b-offers'; // If this only class is set
});
// $offer = $offers[0]; // <---- look here
foreach ($offers as $offer) {
$price = $offer->find('span.b-prices__num', 0)->innertext();
break;
}
仅当我立即使用foreach和break时,它才有效。但是,为什么$ offer = $ offers [0]不起作用?如果以这种方式编写,这里将出现错误:
$price = $offer->find('span.b-prices__num', 0)->innertext();
就像在非对象上调用find()函数一样。
另一个问题是:在使用array_filter函数获取只有一个“ b-offers”类的元素时,是否可以重写代码?我记得我尝试了一些不同的方法,例如
$html->find('div[class="b-offers"]')
或某种类型,但对我不起作用
$offer = $offers[0];
不起作用,因为array_filter
不返回基于0索引的数组。它保留了前一个数组的键。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句