Downloading files using GZIP

谁都会走 提交于 2020-01-30 06:46:28

问题


I have many XML-s and I downloaded using file or file_get_content, but the server administrator told me that through GZIP is more efficient the downloading. My question is how can I include GZIP, because I never did this before, so this solution is really new for me.


回答1:


I don't understand your question.

You say that you downloaded these files - you can't unilaterally enable compression client-side.

OTOH you can control it server-side - and since you've flagged the question as PHP, and it doesn't make any sense for your administrator to recommend compression where you don't have control over the server then I assume this is what you are talking about.

In which case you'd simply do something like:

<?php
ob_start("ob_gzhandler");
...your code for generating the XML goes here

...or maybe this is nothing to do with PHP, and the XML files are static - in which case you'd need to configure your webserver to compress on the fly.

Unless you mean that compression is available on the server and you are fetching data over HTTP using PHP as the client - in which case the server will only compress the data if the client provides an "Accept-Encoding" request header including "gzip". In which case, instead of file_get_contents() you might use:

function gzip_get_contents($url)
{
     $ch=curl_init($url);
     curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $content=curl_exec($ch);
     curl_close($ch);
     return $content;
}



回答2:


You shouldn't need to do any decoding yourself if you use cURL. Just use the basic cURL example code, with the CURLOPT_ENCODING option set to "", and it will automatically request the file using gzip encoding, if the server supports it, and decode it.

Or, if you want the content in a string instead of in a file:

$ch = curl_init("http://www.example.com/");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_ENCODING, "");  // accept any supported encoding

$content = curl_exec($ch);
curl_close($ch);

I've tested this, and it indeed downloads the content in gzipped format and decodes it automatically.

(Also, you should probably include some error handling.)




回答3:


probably curl can get a gzipped file

http://www.php.net/curl

try to use this instead of file_get_contents

edit: tested

curl_setopt($c,CURLOPT_ENCODING,'gzip'); 

then:

gzdecode($responseContent);



回答4:


Send a Accept-Encoding: gzip header in your http request and then uncompress the result as shown here: http://de2.php.net/gzdecode



来源:https://stackoverflow.com/questions/7687210/downloading-files-using-gzip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!