2012-04-29 57 views
4

我试图从file_get_contents(),从stackoverflow api json响应,但回来给我奇怪的字符,如I–%&/mÊ{JõJ×àt¡€ $Ø@ @ìÁÍæ'ìiG#)«*ÊeVe] f @ etc等等。 。file_get_contents和无效字符

好吧,地址为 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-%&/ME {JõJ×àt¡€`$ ...”

感谢您的帮助

回答

2

使用gzdecode来解码压缩的内容。如果您没有gzdecode功能,您应该使用this page的实现。我已检查它是否与要检索的页面一起工作。

2

API响应是gzip压缩。请参阅此页解码响应: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>'; 
} 
+0

感谢杰米,这是一个优雅的解决方案,但cURL不活动的hostig(是一个钻孔),我想实现此功能。 当然,我会在cURL激活的地方使用它。 – Goonie 2012-04-29 11:45:19