[英]html parsing with php DOMDocument
我正在尝试从论坛中提取内容,如果主题超过一页,我想获取所有主题链接,这是主题格式:
<td align="left">
<div class="topicos">
<a href="/_t_1593901" title="Welcome2">
<span class="titulo">
Hello World!
</span>
</a><br>
</div>
</td>
如果它有超过一页,这是主题格式:
<td align="left">
<div class="topicos">
<a href="_t_1594517" title="Welcome">
<span class="titulo">
Hello World!
</span>
</a><br>
</div>
<span class="quickPaging">
[<img src="http://forum.imguol.com//forum/themes/jogos/images/clear.gif" class="master-sprite sprite-icon-minipost" alt="Ir à página" title="Ir à página">
Ir à página:
<a href="/_t_1594517?&page=1">1</a>,
<a href="/_t_1594517?&page=2">2</a>,
<a href="/_t_1594517?&page=3">3</a>,
<a href="/_t_1594517?&page=4">4</a>,
<a href="/_t_1594517?&page=5">5</a>
]</span>
</td>
我想获得 5 页或更多页的主题的 id(_t_1594517),我该怎么做? 这就是我所厌倦的,但我迷路了,我不太了解 DOMDocument 文档,我是编程和 PHP 的新手,求助:
<?php
$html = new DOMDocument();
$url = "http://website.com/forum/?page=";
$page = "1";
while($page <= 10)
{
$html->loadHTML($url + $page);
foreach($html->getElementsByTagName('td') as $td)
{
if($td->hasAttributes())
{
if($td->getAttribute('align') == "left")
{
$div = $td->getElementsByTagName('div');
if($div->hasAttributes())
{
if($td->getAttribute('class') == "topicos")
{
$a = $td->getElementsByTagName('a');
{
if($a->hasAttributes())
{
/*$return['link'][] =*/ echo $a->getElementById('href')->tagName;
}
}
}
}
}
}
}
}
?>
我认为xpath可以帮助你:
如果$with_links
包含带有 5 个链接的 HTML 内容,那么
$doc = new DOMDocument();
$doc->loadHTML($with_links);
$xpath = new DOMXPath($doc);
$quick_paging_links = $xpath->query('//span[@class="quickPaging"]/a[contains(@href,"_t_")]/@href');
if($quick_paging_links->length>4)
{
$first_href = $quick_paging_links->item(0)->value;
$id = substr($first_href, 1, strpos($first_href, '?')-1);
echo 'Topic with id '.$id.' has '.$quick_paging_links->length." links.\n";
}
将产生 output:
Topic with id _t_1594517 has 5 links.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.