gpt4 book ai didi

php - 在xpath/domdocument查询中查找与给定字符串匹配的链接

转载 作者:行者123 更新时间:2023-12-03 16:21:59 25 4
gpt4 key购买 nike

使用Xpath和domDocument获取与给定单词匹配的链接时出现问题。一切似乎都可以在使用for($i=0;$i<$documentLinks->length;$i++){的地方工作。

谁能帮我解决这里的问题?

$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的所有子代,这意味着

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


返回$ e下的第一个链接

$documentLinks = $e->getElementsByTagName('a')->item(0)->nodeValue;
返回该第一个链接的文本。

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

关于php - 在xpath/domdocument查询中查找与给定字符串匹配的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5251282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com