使用 GZIP 下载文件
我有很多 XML-s,我使用 file 或 file_get_content 下载,但服务器管理员告诉我,通过 GZIP 下载效率更高。我的问题是如何包含 GZIP,因为我以前从未这样做过,所以这个解决方案对我来说确实是新的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用 cURL,则不需要自己进行任何解码。只需使用 基本 cURL 示例代码,以及
CURLOPT_ENCODING
选项设置为""
,如果服务器支持,它会自动请求使用 gzip 编码的文件,并对其进行解码。或者,如果您想要字符串中的内容而不是文件中的内容:
我已经对此进行了测试,它确实以 gzipped 格式下载内容并自动对其进行解码。
(此外,您可能应该包含一些错误处理。)
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:
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.)
我不明白你的问题。
你说你下载了这些文件 - 你不能单方面启用压缩客户端。
OTOH,您可以在服务器端控制它 - 并且由于您已将问题标记为 PHP,并且您的管理员在您无法控制的情况下建议压缩是没有任何意义的服务器,那么我想这就是你所说的。
在这种情况下,您只需执行以下操作:
...或者这可能与 PHP 无关,并且 XML 文件是静态的 - 在这种情况下,您需要将 Web 服务器配置为动态压缩。
除非您的意思是服务器上可以进行压缩,并且您使用 PHP 作为客户端通过 HTTP 获取数据 - 在这种情况下,只有当客户端提供包含“gzip”的“Accept-Encoding”请求标头时,服务器才会压缩数据。在这种情况下,您可以使用以下命令代替 file_get_contents():
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:
...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:
也许curl可以获得一个gzip压缩文件
http://www.php.net/curl
尝试使用这个file_get_contents 的
编辑:
然后进行测试:
probably curl can get a gzipped file
http://www.php.net/curl
try to use this instead of file_get_contents
edit: tested
then:
在 http 请求中发送
Accept-Encoding: gzip
标头,然后解压缩结果,如下所示:https://www.php.net/gzdecode
Send a
Accept-Encoding: gzip
header in your http request and then uncompress the result as shown here:https://www.php.net/gzdecode