2011-08-14 52 views
2

如果TD不包含圖像,我需要continue;如果TD不包含圖像,如何忽略/繼續?

我嘗試這樣做:

if(!$image){continue;} 

,但沒有奏效。

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

我該怎麼辦?

回答

2

嘗試:

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

但是,如戈登建議的那樣修改查詢會更有效率。

+0

非常感謝你prodigitalson,你的答案是我需要.. –

2

嘗試用

.//table/tr/td[img] 

或(因爲loadHTML添加一個HTML骨架):

/html/body/table/tr/td[img] 

參見http://codepad.viper-7.com/TsMVxe

+0

非常感謝Gordon,但我需要它在循環內。非常感謝.. –

+0

@ al-dr你爲什麼需要在循環中?爲什麼更好地跳過循環而不是直接抓取那些有img子元素的節點呢? – Gordon

+0

嗨戈登,因爲有時我需要作出條件, if(!$ image){$ image ='default value';} –