在xpath/domdocument查询中查找与给定字符串匹配的链接 [英] Finding links matching given string in xpath/domdocument query
问题描述
使用Xpath和domDocument获取与给定单词匹配的链接时出现问题.一切似乎都可以在使用for($i=0;$i<$documentLinks->length;$i++){
的地方进行.
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") . "\n";
}
}
}
推荐答案
该行:$documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;
应该是:$documentLinks = $e->getElementsByTagName('a');
$e->getElementsByTagName('a')
返回标记为<a ...>
的$ e的所有子项,这表示
returns all children of $e whose tag is <a ...>
which means that
$e->getElementsByTagName('a')->item(0);
返回$ e下的第一个链接
is returning the first link under $e
和$documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;
正在返回该第一个链接的文本.
and $documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;
is returning the text of that first link.
http://php.net/manual/en/domdocument.getelementsbytagname.php
这篇关于在xpath/domdocument查询中查找与给定字符串匹配的链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!