2016-06-10 54 views
0

我有輕微的不同structure.i頁面索引正在通過許多網頁試圖循環,做到以下幾點: -檢查不同的節點和相應的呼應

1.如果td[2]具有跨類THN呼應類。 2.if td[2]具有img節點,然後對srchttp://example.com/img/star01.giff的節點數進行計數並回顯總數。

我能夠做第一部分,但不是第二部分。

pagetype1

<tbody> 

<tr> 
    <td>Name1</td> 
    <td> 
     <span class="star5-05"> 
    </td> 
</tr> 
<tr> 
    <td>Name2</td> 
    <td> 
     <span class="star5-05"> 
    </td> 
</tr> 
</tbody> 

pagetype2

<tbody> 
    <tr> 
     <td>Name1</td> 
     <td> 
      <img alt="" src="http://example.com/img/star01.gif"> 
      <img alt="" src="http://example.com/img/star01.gif"> 
      <img alt="" src="http://example.com/img/star01.gif"> 
      <img alt="" src="http://example.com/img/star01.gif"> 
      <img alt="" src="http://example.com/img/star02.gif"> 
     </td> 
    </tr> 
    <tr> 
     <td>Name2</td> 
     <td> 
      <img alt="" src="http://example.comimg/star01.gif"> 
      <img alt="" src="http://example.comimg/star01.gif"> 
      <img alt="" src="http://example.comimg/star01.gif"> 
      <img alt="" src="http://example.comimg/star01.gif"> 
      <img alt="" src="http://example.com/img/star02.gif"> 
     </td> 
    </tr> 
    </tbody> 

我的代碼

foreach($my_nodes as $my_node) 
    { 
    $tmp=$my_xpath->query('td[1]',$my_node); 

    if ($tmp->length>0) 
     { 
     $tmp=$tmp->item(0)->textContent; 

     if ($tmp=="Name1") 
      { 
      $chkstars=$my_xpath->query('td[2]/span/@class',$my_node); 
      if ($chkstars->length>0) 
       { 
       $tmp_stars=$chkstars->item(0)->textContent; 
       } 
       else 
       { 
       $tmp_stars=$my_xpath->evaluate('count(//td[2]/img[@src="http://www.example.com/img/star01.gif"]),$my_node)'); 
       } 
      echo $tmp_stars."<br>"; 
      } 

     } 

    } 
+0

'$ my_xpath->評估('計數(// IMG [@ SRC =「HTTP:/ /example.comimg/star01.gif「]));' – splash58

+0

在哪裏我應該把這個計數(// img [@ src =」http://example.comimg/star01.gif「]) –

+0

或者如果你想只計算該行的img - '$ my_xpath-> evaluate('count(.mimg [@ src =「http://example.comimg/star01.gif」]),$ my_node);' – splash58

回答

1

事實上,unswer是Xpath count(.//img[@src="http://example.comimg/star01.gif"])。僅用於測試目的的所有代碼

$my_xpath = new DOMXPath($my_doc); 
$my_nodes = $my_xpath->query('//tbody/tr'); 
foreach($my_nodes as $my_node) 
{ 
$tmp=$my_xpath->query('td[2]',$my_node); 
    if ($tmp->length>0) 
    { 
    $tmp=$tmp->item(0)->textContent;  
     if ($chkstars=$my_xpath->evaluate('string(td[2]/span/@class)',$my_node)) 
       echo 'class: ' . $chkstars . "\n"; 
     if($count = $my_xpath->evaluate('count(.//img[@src="http://example.comimg/star01.gif"])',$my‌​_node)) 
       echo 'count: ' . $count . "\n"; 
    } 
} 

demo(更改爲STR1或str所不同的XML))

+0

我改變了代碼... plz se我的代碼...它仍然沒有正確回聲...我需要它回顯tmp_stars如果td [1]是Name1 –

+0

https://eval.in/586688 – splash58