Javascript 如何用 PHP 压缩 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2037349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compress JSON with PHP?
提问by Vilx-
I'm writing a little analysis page which will help me hunt down bugs in an application. In essence it allows to visually compare actual data and log entries, plus perform a bit of analysis on the data.
我正在编写一个小分析页面,它将帮助我寻找应用程序中的错误。从本质上讲,它允许直观地比较实际数据和日志条目,并对数据进行一些分析。
Since this is for debugging only and since I will be deploying this on the live site I want it to have as little server load as possible. Several of the analysis options will include rather heavy substring searching or n2operations, so I'm going to offload this to the client.
由于这仅用于调试并且我将在实时站点上部署它,因此我希望它具有尽可能少的服务器负载。几个分析选项将包括相当繁重的子字符串搜索或 n 2 个操作,因此我将把它卸载给客户端。
This means that the PHP page will just take the data from the tables and logs, JSON some of it, and write it out. The client Javascript will then do all the analysis etc.
这意味着 PHP 页面只会从表和日志中获取数据,其中一些是 JSON,然后将其写出。然后客户端 Javascript 将进行所有分析等。
The problem is that the JSON'ed data will be several MB large, and my connection to the server - slow. It would be nice to compress the data somehow. Anyone have ideas?
问题是 JSON 数据将有几 MB 大,而且我与服务器的连接很慢。以某种方式压缩数据会很好。有人有想法吗?
The environment is PHP + Apache; I don't know if mod_gzip will be installed; and I have no control over it.
环境为PHP+Apache;不知道会不会安装mod_gzip;我无法控制它。
回答by Gumbo
You can compress the data with PHP's output control. Just put this call at the start of your script before any output:
您可以使用PHP 的输出控件来压缩数据。只需在任何输出之前将此调用放在脚本的开头即可:
ob_start('ob_gzhandler');
Now any output will be compressed with either gzipor deflateif accepted by the client.
现在,如果客户端接受,任何输出都将使用gzip或deflate进行压缩。
回答by user956584
In PHP 5.4 is now JSON_UNESCAPED_UNICODE so you can replace char:
在 PHP 5.4 中现在是 JSON_UNESCAPED_UNICODE 所以你可以替换字符:
\u00f3 -> ?? = ?
\u00f3 -> ?? = ?
eq:
等式:
json_encode($data,JSON_UNESCAPED_UNICODE);
回答by userlond
If apache is your choice (and it is, like mentioned in original question), you may add some rules into .htaccess:
如果 apache 是您的选择(就像在原始问题中提到的那样),您可以在 .htaccess 中添加一些规则:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
# Add any mime-type you think is appropriate here
AddOutputFilterByType DEFLATE application/json
</IfModule>

