Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

php - Finding links matching given string in xpath/domdocument query

Having issues getting links that match a given word to display using Xpath and domDocument. Everything seems to work up to where for($i=0;$i<$documentLinks->length;$i++){ is used.

Can anyone help with where I am going wrong here?

$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") . "
";
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

should probably be: $documentLinks = $e->getElementsByTagName('a');


$e->getElementsByTagName('a')

returns all children of $e whose tag is <a ...> which means that

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

is returning the first link under $e

and $documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue; is returning the text of that first link.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...