HTML DOM 解析器 - 如何获取论坛中所有主题的第一篇文章

发布于 2024-10-21 09:14:50 字数 902 浏览 8 评论 0原文

我试图废弃 sitepoint javascript 论坛中每个主题的第一篇文章。但是 DOM 解析器会给我 SITE POINT JAVASCRIPT 论坛中每个主题的所有帖子。也许我没有正确遍历 DOM?下面是我的代码:

<?php

class Sitepoint extends Controller
{
    public function index()
    {
        $this->load->helper('dom');
        header('Content-Type: text/html; charset=utf-8');
        echo '<ol>';

            $html = file_get_html('http://www.sitepoint.com/forums/javascript-15');

            foreach($html->find('a[id^="thread_title"]') as $topic) {
                $post =$topic->href;
                $posthtml = file_get_html($post);
                $posthtml->find('div[id^="post_message"]', 0);
                echo'<li>';
                echo $topic->plaintext.'<br>';
                echo $posthtml->plaintext.'<br>';
                echo'</li>';
            }
        echo '</ol>';
    }
}

I was trying to scrap the first post of every topics in sitepoint javascript forum. But The DOM Parser would give me ALL THE POSTS OF EVERY TOPICS IN SITE POINT JAVASCRIPT FORUM. Maybe I didn't traverse the DOM correctly ? Below is my code:

<?php

class Sitepoint extends Controller
{
    public function index()
    {
        $this->load->helper('dom');
        header('Content-Type: text/html; charset=utf-8');
        echo '<ol>';

            $html = file_get_html('http://www.sitepoint.com/forums/javascript-15');

            foreach($html->find('a[id^="thread_title"]') as $topic) {
                $post =$topic->href;
                $posthtml = file_get_html($post);
                $posthtml->find('div[id^="post_message"]', 0);
                echo'<li>';
                echo $topic->plaintext.'<br>';
                echo $posthtml->plaintext.'<br>';
                echo'</li>';
            }
        echo '</ol>';
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请你别敷衍 2024-10-28 09:14:50

您忘记将 $posthtml->find 的结果分配给变量:

foreach($html->find('a[id^="thread_title"]') as $topic) {
    $post =$topic->href;
    $posthtml = file_get_html($post);
    $posttext = $posthtml->find('div[id^="post_message_"]', 0);
    echo'<li>';
    echo $topic->plaintext.'<br>';
    echo $posttext->plaintext.'<br>';
    echo'</li>';
}

You forgot to assign the result of $posthtml->find to a variable:

foreach($html->find('a[id^="thread_title"]') as $topic) {
    $post =$topic->href;
    $posthtml = file_get_html($post);
    $posttext = $posthtml->find('div[id^="post_message_"]', 0);
    echo'<li>';
    echo $topic->plaintext.'<br>';
    echo $posttext->plaintext.'<br>';
    echo'</li>';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文