2013-10-04 38 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;