2015-10-17 35 views
4

我希望能夠做的查找與PHP簡單DOM解析器直接後裔

$html->find("#foo>ul") 

但PHP簡單DOM庫不承認「立即後代」選擇>相當於等查找所有<ul>項下的#foo包括那些在dom中嵌套更深的項目。

你會推薦什麼作爲抓住特定類型直系後代的最佳方法?

+0

你剛接近解決方案:) – Mubin

+1

我使用的是phpquery。它是一個包含DOM解析器的包裝器,可以讓你使用任意的css3選擇器https://code.google.com/p/phpquery/ – chiliNUT

+1

@chiliNUT大喊,像魅力一樣工作。例如:'pq('div> h3') - > elements [1] - > textContent' – Leo

回答

3

您可以使用DomElementFilter在一些大教堂分支獲取節點所需的類型。這說明如下:

PHP DOM: How to get child elements by tag name in an elegant manner?

或自己做所有的childNodes定期循環和過濾,然後通過他們的標籤名稱:

foreach ($parent->childNodes as $node) 
    if ($node->nodeName == "tagname1") 
     ... 
+1

謝謝...這讓我在正確的方向,這是做一個普遍的查詢'兒童'的節點,然後檢查標籤名稱。 – user1104799

1

HTML片斷

<div id="foo"> 
    <ul> 
     <li>1</li> 
    </ul>  
    <ul> 
     <li>2</li> 
    </ul>  
    <ul> 
     <li>3</li> 
    </ul>  
</div> 

PHP代碼來獲得FIRST <ul>

echo $html->find('#foo>ul', 0); 

這將輸出

<ul> 
    <li>1</li> 
</ul> 

但如果你想要得到的只是1 FR OM第一<ul>

echo $html->find('#foo>ul', 0)->plaintext; 
+0

Thanks Mubin - 我的情況是嵌套了UL的,所以find(#foo> ul)只是拾取所有UL #foo,不只是頂級的(php dom不關注'>') – user1104799

0

只是分享我在相關的帖子找到了解決方案,並把它概括地說: 「查找與PHP簡單DOM解析器直接子」都與工程...

... PHP簡單DOM:

//if there is only one div containing your searched tag 
    foreach ($html->find('div.with-given-class')[0]->children() as $div_with_given_class) { 
     if ($div_with_given_class->tag == 'tag-you-are-searching-for') { 
     $output [] = $div_with_given_class->plaintext; //or whatever you want 
     } 
    } 


    //if there are more divs with a given class (better solution) 
    $all_divs_with_given_class = 
     $html->find('div.with-given-class'); 

    foreach ($all_divs_with_given_class as $single_div_with_given_class) { 
     foreach ($single_div_with_given_class->children() as $children) { 
      if ($children->tag == 'tag-you-are-searching-for') { 
       $output [] = $children->plaintext; //or whatever you want 
      } 
     } 
    } 

...也PHP DOM/XPath的:

$all_divs_with_given_class =  
     $xpath->query("//div[@class='with-given-class']/tag-you-are-searching-for"); 

    if (!is_null($all_divs_with_given_class)) { 
     foreach ($all_divs_with_given_class as $tag-you-are-searching-for) { 
      $ouput [] = $tag-you-are-searching-for->nodeValue; //or whatever you want 
     } 
    } 

請注意,您必須使用單斜槓 「/」 中的XPath找到唯一直接後裔。