Extract an attribute from a specific element in DOM
I want to be able to extract only the src
of the second image in an html file. I am using the PHP DOM parser:
foreach($html->find('img[src]') as $element)
$src开发者_开发知识库 = $element->getAttribute('src');
echo $src;
However, I am getting the src
of the last image in the page, instead of the one I am looking for.
Can I display only a specific src
outside of the foreach
loop?
Your loop is missing {}, it is equivalent to
foreach($html->find('img[src]') as $element) {
$src = $element->getAttribute('src');
}
echo $src;
so, the echo gets the $src after the last iteration of your loop, which is the last element.
Using the example from their website, I'd go with this (braces are key here):
$count = 1;
foreach($html->find('img') as $element) {
if ($count == 2) {
echo $element->src;
break;
}
$count += 1;
}
精彩评论