2013-04-27 46 views
1

我解析,並從加農DOM解析器HTML DOM字符串,並希望得到下一個元素的純文本匹配時前一個元素上找到如我的HTML下一個元素就像PHP加農DOM解析器得到時發現匹配

<tr class="last even"> 
    <th class="label">SKU</th> 
    <td class="data last">some sku here i want to get </td> 
</tr> 

我用下面的代碼現在

$html = str_get_dom('html string here'); 
foreach ($html('th.label') as $elem){ 
       if($elem->getPlainText()=='SKU'){ //this is right 
        echo $elem->getSibling(1)->getPlainText(); // this is not working 
       } 
      } 

如果發現有類拉布勒和innerHTML的SKU的次然後得到一個同級的innerHTML是SKU值

請幫忙整理一下。

+0

'$ html()'?變量函數?當我走出我的眼睛時執行我。 – 2013-04-27 21:32:30

+0

@MarcB https://code.google.com/p/ganon/wiki/AccesElements – 2013-04-27 21:45:21

+0

是的,我知道。我的評論仍然成立。變量函數是邪惡的,就像變量變量一樣。 – 2013-04-27 21:45:53

回答

3

這可能是在HTML的「加農」的錯誤 - 如果你把你的HTML的例子:

$html = '<table> 
       <tr class="last even"> 
        <th class="label">SKU</th> 
        <td class="data last">some sku here i want to get </td> 
       </tr> 
      </table>'; 

    $html = str_get_dom($html); 

,因爲在html「加農」的新生產線的某種原因認爲,下一個元素是一個文本元素,只有再有就是希望TD - 讓你不得不這樣做:

foreach ($html('th.label') as $elem){ 
     if($elem->getPlainText()=='SKU'){ 
      //elem -> text node -> td node 
      echo($elem->getSibling(1)->getSibling(1)->getPlainText()); 
     } 
    } 

如果你組織你的HTML像這樣(不換行):

$html = '<table> 
       <tr class="last even"> 
        <th class="label">SKU</th><td class="data last">some sku here i want to get </td> 
       </tr> 
      </table>'; 

然後你原來的代碼將工作$elem->getSibling(1)->getPlainText()

也許考慮使用php simple html dom類 - 它更加直觀,使用全接力方式,jQuery的DOM解析器喜歡和不使用這種可怕的無功函數法:):

require('simple_html_dom.php'); 

    $html = '<table> 
       <tr class="last even"> 
        <th class="label">SKU</th> 
        <td class="data last">some sku here i want to get </td> 
       </tr> 
      </table>'; 

    $dom = str_get_html($html); 


    foreach($dom->find('th.label') as $el){ 
     if($el->plaintext == 'SKU'){ 
      echo($el->next_sibling()->plaintext); 
     } 
    } 
+0

此前我已經使用了簡單的html dom解析器,但其非常,我不能加載我的整個頁面的HTML DOM,併發送超時..非常慢從這累。 – 2013-04-28 05:41:23

+0

非常感謝$ elem-> getSibling(1) - > getSibling(1) - > getPlainText()它的工作。 – 2013-04-28 05:43:34

+0

任何想法獲取javascript內容使用加納我有我的js喜歡 謝謝 – 2013-04-28 05:46:37