Reputation: 5353
When I parse some html and get an array of html elements I want to get the first item. Here is the code:
$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;
}
It works only if I use foreach and the break immediately. But why $offer = $offers[0] doesnt work? If I write this way there will be an error here:
$price = $offer->find('span.b-prices__num', 0)->innertext();
Like call find() function on a non-object.
Also another question is: is it possible to rewrite the code where I use array_filter function to get an element which has only one class "b-offers"? I remember I tried some different approaches like
$html->find('div[class="b-offers"]')
or kind of, but it didn't work for me
Upvotes: 0
Views: 1088
Reputation: 987
why $offer = $offers[0] doesnt work?
I think because at this point $offers
is still an object and not an array
to get an element which has only one class "b-offers"
try $html->find('div.b-offers');
Upvotes: 0
Reputation: 13525
$offer = $offers[0];
doesn't work because array_filter
doesn't return a 0-index based array. it preserves the key of the previous array.
Upvotes: 1