开发者

Downloading files using GZIP

开发者 https://www.devze.com 2023-04-11 05:10 出处:网络
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, beca

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 n开发者_如何学编程ew for me.


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.)


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


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);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号