phpcontinuedomxpath

How to ignore/continue if TD does not contain an image?


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>
                    <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?


Solution

  • Try:

    if(!count($image)){continue;}

    But it would be much more efficient to modify your query as Gordon suggested.