我正在尝试使用 file_get_contents() 从堆栈溢出 api 获取 json 响应,但回到我身边奇怪的字符,例如I–%&/mÊ{JõJ×àt¡€
$Ø@ìÁ ˆÍæ'ìiG#)«*ÊeVe]f@ 等......
好的,地址 http://api.stackoverflow.com/1.1/users/779187/
我的代码是
$json_res = json_decode(file_get_contents("http://api.stackoverflow.com/1.1/users/779187/"))
显然,json_dec的响应为 NULL,因为字符串不是 JSON。我也尝试在没有json_decode的情况下直接转储值,结果是"I–%&/mÊ{JõJ×àt¡€$..."
感谢您的帮助
使用 gzdecode
解码压缩内容。如果您没有 gzdecode 函数,则应使用此页面中的实现。我已经检查了它是否适用于您要检索的页面。
API 响应是 GZIP'd。请参阅此页面以解码响应:http://api.stackoverflow.com/1.1/usage/gzip
如果切换到 cURL,则可以使用 CURLOPT_ENCODING 选项对其进行解码。
$url = 'http://api.stackoverflow.com/1.1/users/779187/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, 1);
$output = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($status=='200') {
$data = json_decode($output);
echo '<pre>' . print_r($data,true) . '</pre>';
}
先用gzinflate
解压缩它。