gpt4 book ai didi

PHP DomXPath - 按类获取子级

转载 作者:行者123 更新时间:2023-12-03 17:04:57 25 4
gpt4 key购买 nike

到目前为止,我的代码正在使用 xPath 查询获取所有类“forumRow”。如何获得在每个“forumRow”类中存在一次的 a 元素的 href 属性?

我有点卡在我可以从第一个查询的结果开始运行查询的地步。

我当前的代码

            $this -> boards = array();
$html = @file_get_contents('http://www.roblox.com/Forum/Default.aspx');

libxml_use_internal_errors(true);
$page = new DOMDocument();
$page -> preserveWhiteSpace = false;
$page -> loadHTML($html);

$xpath = new DomXPath($page);
$board_array = $xpath -> query('//*[@class="forumRow"]');

foreach($board_array as $board)
{
$childNodes = $board -> childNodes;
$boardName = $childNodes -> item(0) -> nodeValue;

if (strlen($boardName) > 0)
{

$boardDesc = $childNodes -> item(1) -> nodeValue;
array_push($this -> boards, array($boardName, $boardDesc));
}
}
$Cache -> saveData(json_encode($this -> boards));

最佳答案

遗憾的是,我无法让您的代码正常工作(关于 forumRow <td> 的摘录) - 所以我编造了这个:

$html = @file_get_contents('http://www.roblox.com/Forum/Default.aspx');
libxml_use_internal_errors(true);
$page = new DOMDocument();
$page->preserveWhiteSpace = false;
$page->loadHTML($html);
$xpath = new DomXPath($page);

foreach($xpath->query('//td[@class="forumRow"]') as $element){
$links=$element->getElementsByTagName('a');
foreach($links as $a) {
echo $a->getAttribute('href').'<br>';
}
}

生产

/Forum/Search/default.aspx
/Forum/ShowForum.aspx?ForumID=46
/Forum/ShowForum.aspx?ForumID=14
/Forum/ShowForum.aspx?ForumID=44
/Forum/ShowForum.aspx?ForumID=43
/Forum/ShowForum.aspx?ForumID=45
/Forum/ShowForum.aspx?ForumID=21
/Forum/ShowForum.aspx?ForumID=13
...
a very long list



来自 <td class="forumRow">..<a href= ... ></a>..</td>的所有href

关于PHP DomXPath - 按类获取子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19184903/

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