【问题标题】:html parsing with php DOMDocument用 php DOMDocument 解析 html
【发布时间】:2011-10-11 04:59:32
【问题描述】:

我正在尝试从论坛中提取内容,如果主题超过一页,我想获取所有主题链接,这是主题格式:

<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?&amp;page=1">1</a>,&nbsp;
<a href="/_t_1594517?&amp;page=2">2</a>,&nbsp;
<a href="/_t_1594517?&amp;page=3">3</a>,&nbsp;
<a href="/_t_1594517?&amp;page=4">4</a>,&nbsp;
<a href="/_t_1594517?&amp;page=5">5</a>&nbsp;
]</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;
                        }
                    }
                }
            }
        }
    }
}   
}
?>

【问题讨论】:

  • 为什么不用jQuery呢?
  • 我正在学习PHP,所以我想用php 呵呵,谢谢anwyways

标签: php html tags html-parsing domdocument


【解决方案1】:

我觉得xpath可以帮到你:

如果$with_links 的 HTML 内容包含 5 个链接,那么

$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";
}

将产生输出:

Topic with id _t_1594517 has 5 links.

【讨论】:

    猜你喜欢
    • 2013-02-08
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    相关资源
    最近更新 更多