php
  • domdocument
  • xpath
  • 2011-03-09 89 views 2 likes 
    2

    獲取與使用Xpath和domDocument顯示的給定單詞匹配的鏈接時出現問題。一切似乎都在使用for($i=0;$i<$documentLinks->length;$i++){在xpath/domdocument查詢中查找與給定字符串匹配的鏈接

    任何人都可以幫助我在哪裏出錯嗎?

    $html = '<ol>'; 
    $html .= ' <li id="stuff-123"> some copy here </li>'; 
    $html .= ' <li id="stuff-456"> some copy here <a href="http://domain.com">domain</a> </li>'; 
    $html .= ' <li id="stuff-789"> some copy here </li>'; 
    $html .= '</ol>'; 
    
    
        $dom = new DOMDocument(); 
        $dom->loadHTML($html); 
        $xpath = new DOMXPath($dom); 
        $result = $xpath->query('//ol/li[starts-with(@id, "stuff")]'); 
        foreach($result as $e){ 
         $documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue; 
         for($i=0;$i<$documentLinks->length;$i++){ 
          $documentLink = $documentLinks->item($i); 
          if(preg_match("/domain/i", $documentLink->getAttribute("href"))){ 
           echo $documentLink->getAttribute("href") . "\n"; 
          } 
         } 
        } 
    
    +1

    是不是'$ documentLinks'根據http://www.php.net/manual/en/class.domnode.php – 2011-03-09 20:22:34

    回答

    1

    行:$documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;

    也許應該是:$documentLinks = $e->getElementsByTagName('a');


    $e->getElementsByTagName('a') 
    

    返回所有$ê其標記爲<a ...>這意味着

    $e->getElementsByTagName('a')->item(0); 
    
    兒童

    正在返回$ e下的第一個鏈接e

    $documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue; 正在返回該第一個鏈接的文本。

    http://php.net/manual/en/domdocument.getelementsbytagname.php

    +0

    感謝mlaw,這樣做了一個字符串。 – 2011-03-09 20:32:18

    1

    您可以直接通過XPath的

    //ol/li[starts-with(@id, "stuff")]/a[contains(@href, "domain")]/@href 
    

    獲取href屬性,然後就做

    foreach($result as $href){ 
        echo $href->nodeValue; 
    } 
    

    注意contains功能是區分大小寫的,但。

    相關問題