php DomXPath - how to get image in current node only and not in child nodes?
i need to get only image that in current node and not in child nodes
i want to get onlygreen/yellow/red/black
images without not_important.gif
image
i can use query './/table/tr/td/img'
but i need it inside loop
<?php
/////////////////////////////////////////////////////////////////////
$html='
<table>
<tr>
<td colspan="2">
<span>
<img src="not_important.gif" />
</span>
<img src="green.gi开发者_如何学编程f" />
</td>
</tr>
<tr>
<td>
<span>yellow</span>
<img src="yellow.gif" />
</td>
<td>
<span>red</span>
<img src="red.gif" />
</td>
</tr>
</table>
<table>
<tr>
<td>
<span>
<img src="not_important.gif" />
</span>
<img src="black.gif" />
</td>
</tr>
</table>
';
/////////////////////////////////////////////////////////////////////
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DomXPath($dom);
/////////////////////////////////////////////////////////////////////
$query = $xpath->query('.//table/tr/td');
for( $x=0,$results=''; $x<$query->length; $x++ )
{
$x1=$x+1;
$image = $query->item($x)->getELementsByTagName('img')->item(0)->getAttribute('src');
$results .= "image $x1 is : $image<br/>";
}
echo $results;
/////////////////////////////////////////////////////////////////////
?>
can i do it through $query->item()->
has_attributes
and getElementsByTagNameNS
and getElementById
but i failed ::Replace:
$image = $query->item($x)->getELementsByTagName('img')->item(0)->getAttribute('src');
...with:
$td = $query->item($x); // grab the td element
$img = $xpath->query('./img',$td)->item(0); // grab the first direct img child element
$image = $img->getAttribute('src'); // grab the source of the image
In other words, use the XPath
object again to query, but now for ./img
, relative to the context node you provide as the second argument to query()
. The context node being one of the elements (td
) of the earlier result.
The query //table/tr/td/img
should work just fine as the unwanted images all reside in <span>
elements.
Your loop would look like
$images = $xpath->query('//table/tr/td/img');
$results = '';
for ($i = 0; $i < $images->length; $i++) {
$results .= sprintf('image %d is: %s<br />',
$i + 1,
$images->item($i)->getAttribute('src'));
}
精彩评论