2013-10-04 41 views
1

到目前为止,我的代码使用xPath查询获取所有类的'forumRow'。我如何获得每个'forumRow'类中存在的a元素的href属性?PHP DomXPath - 按类别获取子项

我有点卡住了,我可以从第一个查询的结果开始运行查询。

我当前的代码

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

回答

2

可悲的是,我不能让你的代码工作(关于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?Fo rumID = 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
...
一个很长的名单

所有从<td class="forumRow">..<a href= ... ></a>..</td>

的HREFs
0

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

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