2

So far, my code is getting all classes 'forumRow' using a xPath query. How would I get the href-attribute of the a-element which exists once in every 'forumRow' class?

I'm kinda stuck at the point where I can run a query starting from the result of the first query.

My current code

            $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));
4

2 回答 2

4

可悲的是,我无法让您的代码正常工作(关于 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
...
很长的列表

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

于 2013-10-04T15:48:11.907 回答
0

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

$childNodes = $board -> childNodes;
return; // <-- remove this line
$boardName = $childNodes -> item(0) -> nodeValue;
于 2013-10-04T17:29:40.720 回答