![](/img/trans.png)
[英]php DomXPath - how to get image in current node only and not in child nodes?
[英]PHP DomXPath - Get Child by Class
到目前为止,我的代码使用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
...
很长的清单
来自<td class="forumRow">..<a href= ... ></a>..</td>
函数中间有一个return
权限,因此数组永远不会被填充,也不会saveData(...)
。 只需删除此行,您的代码似乎可以正常工作。 ;)
$childNodes = $board -> childNodes;
return; // <-- remove this line
$boardName = $childNodes -> item(0) -> nodeValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.