【问题标题】:How to enable gzip compression using PHP Simple HTML DOM Parser如何使用 PHP Simple HTML DOM Parser 启用 gzip 压缩
【发布时间】:2010-05-26 16:08:33
【问题描述】:

我尝试了一些方法来使用 PHP Simple HTML DOM Parser 启用 gzip 压缩,但到目前为止似乎没有任何效果。使用 ini_set 我已经设法更改用户代理,所以我认为也可以启用 gzip 压缩?

include("simpdom/simple_html_dom.php");
ini_set('zlib.output_compression', 'On');   
$url = 'http://www.whatsmyip.org/http_compression/';
$html = file_get_html($url);
print $html;

上面的网站对其进行了测试。如果我完全错误地处理这个问题,请告诉我。

====

更新

对于其他试图实现相同目标的人,最好只使用 cURL,然后像这样使用 dom 解析器:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // Define target site
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // Return page in string
curl_setopt($cr, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2');
curl_setopt($ch, CURLOPT_ENCODING , "gzip");     
curl_setopt($ch, CURLOPT_TIMEOUT,5); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // Follow redirects

$return = curl_exec($ch); 
$info = curl_getinfo($ch); 
curl_close($ch); 

$html = str_get_html("$return");

【问题讨论】:

    标签: php dom gzip


    【解决方案1】:

    CURLOPT_ENCODING 以便响应返回返回(接受为)gzip 压缩数据 - 服务器设置(ob_start("ob_gzhandler") 或 php_ini..)告诉服务器输出 gzip 压缩数据。

    就像您使用不支持 gzip 的浏览器访问该页面一样。要接受 gzip 数据,您必须使用 curl 以便进行区分。

    【讨论】:

    • 感谢丹的澄清。我用 file_get_html 测试了你的方法,但它仍然没有用。好像没有捷径,必须先用curl。
    【解决方案2】:

    只需在输出数据的 PHP 脚本的最顶部添加以下行:

      ob_start("ob_gzhandler");
    

    Reference

    -------更新--------

    您还可以尝试通过 .htaccess 文件在站点范围内启用 gzip 压缩。像这样的东西应该 gzip 您的网站内容,但图像:

    # Insert filter
    SetOutputFilter DEFLATE
    
    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    
    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    
    # MSIE masquerades as Netscape, but it is fine
    # BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    
    # NOTE: Due to a bug in mod_setenvif up to Apache 2.0.48
    # the above regex won't work. You can use the following
    # workaround to get the desired effect:
    BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html
    
    # Don't compress images
    #SetEnvIfNoCase Request_URI \
    \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    
    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary
    

    【讨论】:

    • 感谢您的回复,但是,根据该压缩测试页面。 . .它说它仍然无法正常工作。我可以使压缩工作的唯一方法是使用 cURL。 curl_setopt($ch, CURLOPT_ENCODING , "gzip");还有其他想法吗?
    • Pablo - 很棒的代码 :) 但请记住,在这种情况下,他是在“请求”gzip 内容,而不是发送它。他要去另一台服务器,询问数据并试图说“把它压缩给我,我可以处理它”。
    猜你喜欢
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 2012-04-08
    • 2017-06-08
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多