PHP DomXPath - 按类获取孩子


PHP DomXPath - Get Child by Class

到目前为止,我的代码正在使用xPath查询获取所有类'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));

可悲的是,我无法让你的代码工作(关于论坛行<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>';
    }
}

生产

/

论坛/搜索/默认.aspx
/论坛/展会论坛.aspx?论坛 ID=46
/论坛/展会论坛.aspx?论坛 ID=14
/论坛/展会论坛.aspx?论坛 ID=44
/论坛/展会论坛.aspx?论坛 ID=43
/论坛/展会论坛.aspx?论坛 ID=45
/论坛/展会论坛.aspx?论坛 ID=21
/论坛/展会论坛.aspx?论坛 ID=13
...
很长的清单

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

函数中间有一个return,因此数组永远不会被填充,也不会被调用saveData(...)。只需删除此行,您的代码似乎就可以工作。;)

$childNodes = $board -> childNodes;
return; // <-- remove this line
$boardName = $childNodes -> item(0) -> nodeValue;