Php Simplehtmldom获取第一个元素
当我解析一些html并得到一个html元素数组时,我想得到第一项。代码如下:Php Simplehtmldom获取第一个元素,php,simple-html-dom,Php,Simple Html Dom,当我解析一些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 s
$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;
}
类似于对非对象调用find()函数
另外一个问题是:是否可以重写代码,其中我使用array_filter函数来获取只有一个类“b-offers”的元素?我记得我试过一些不同的方法,比如
$html->find('div[class="b-offers"]')
或者某种程度上,但它对我不起作用
$offer=$offers[0]代码>不起作用,因为数组\u筛选器
不返回基于0索引的数组。它保留上一个数组的键 为什么$offer=$offers[0]不起作用?
我认为,因为此时,$offers
仍然是一个对象,而不是数组
获取只有一个类“b-offers”的元素
尝试$html->find('div.b-offers')代码>Hm,但是当我按照DebZer0的答案回答时,我能够得到第一个元素,我只写$offer=reset($offers)。好吧,我试着按照你说的做(查找div.b-offers),但我想我也得到了类似“b-offers other class”这样的元素。。
$html->find('div[class="b-offers"]')