dqwh1119 2013-02-14 18:38
浏览 104
已采纳

php在使用SimpleHTMLDOM渲染之前抓取页面的内容

OK, the title is vague but i just dont know how to word this.

what I want to do is parse the entire page before rendering, then select a certain div from the page using Simple HTML DOM PHP and render that instead of the entire page, if the header of the page matches through if(isset($_SERVER[] call

Trouble is, i dont know how to do it, i cant select the current page using PHP (using $_SERVER[]?). I dont even know if I'm making sense.

say we start with how the external library works:

$html = file_get_html(''); // Get HTML of this page.. somehow
$div = $html->find('div[id=mainContent]'); // or 'div#mainContent'

But how do I echo the contents of that div? and will this render the page first?

Can anyone help me?

  • 写回答

3条回答 默认 最新

  • dongxingdu9594 2013-02-14 20:29
    关注

    You can obtain this in a cleaner way using, as suggested, ob_get_contents. With appropriate use of core PHP directives and inclusion, you can make it so you don't have to touch the existing PHP files at all!

    <?php
        // This goes before the page, and this can be done automatically (i.e. without
        // modifying the existing PHP file) using auto prepend:
        // http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
        ob_start();
    ?>
    
    // The "old" page ...
    
    <?php
        // This goes after the page, and again can be done automatically using
        // auto append (see above).
        // This 'if' can also check whether this page is one of those that must be
        // manipulated, or not.
        if(!isset($_SERVER['EXAMPLE_HEADER']) || ('false'==$_SERVER['EXAMPLE_HEADER']))
        {
            $html = ob_get_clean();
    
            // Include is only necessary in this scope -- full path may be needed, though
            include_once('simple_html_dom.php');
    
            // Here, $html is parsed to yield a DOM object
            // ...
    
            foreach($dom->find('div[id=mainContent]') as $div)
            {
                echo $div->innertext;
            }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)