I need to continue;
if TD
does not contain an image.
I tried this:
if(!$image){continue;}
but that did not work.
<?php
/////////////////////////////////////////////////////////////////////
$html='
<table>
<tr>
开发者_StackOverflow社区 <td colspan="2">
<span>green</span>
<img src="green.gif" />
</td>
</tr>
<tr>
<td>
<span>yellow</span>
no image !!
</td>
<td>
<span>red</span>
<img src="red.gif" />
</td>
</tr>
</table>
<table>
<tr>
<td>
<span>black</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;
$color = $query->item($x)->getElementsByTagName('span')->item(0)->nodeValue;
$image = $query->item($x)->getELementsByTagName('img');
if(!$image){continue;}
$image = $image->item(0)->getAttribute('src');
$results .= "color $x1 is : $color - and- image $x1 is : $image<br/>";
}
echo $results;
/////////////////////////////////////////////////////////////////////
?>
How can I go about this?
Try:
if(!count($image)){continue;}
But it would be much more efficient to modify your query as Gordon suggested.
Try with
.//table/tr/td[img]
or (since loadHTML adds an HTML skeleton):
/html/body/table/tr/td[img]
See http://codepad.viper-7.com/TsMVxe
精彩评论