2

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?

kaya3
  • 47,440
  • 4
  • 68
  • 97
al-dr
  • 147
  • 1
  • 3
  • 10

2 Answers2

2

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

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • @al-dr why do you need it in the loop? Why is that better to skip in the loop instead of directly fetching only those nodes that do have an img child element? – Gordon Aug 14 '11 at 08:19
  • hi Gordon, because sometimes i need to make conditional, if (!$image){$image='default value';} – al-dr Aug 14 '11 at 09:10
  • @al-dr well, you should have explained that in the question then because you only asked how to ignore/continue it and not how to set a default. – Gordon Aug 14 '11 at 09:14
  • not just for set default value, it just for example .. and about your note, you are right +1 . next time i will :: – al-dr Aug 14 '11 at 09:22
2

Try:

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

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

prodigitalson
  • 60,050
  • 10
  • 100
  • 114