解析 JSON 时的空结果
Empty result when parsing a JSON
我讨厌问这种问题,因为我知道答案一定非常简单,但我似乎想不出来。
我正在尝试解析来自 Stack Exchange API
的 JSON 响应,但结果是我得到一个空字符串,即使我检查了 URL 和 JSON 格式化,一切似乎都有效。
我使用的代码很简单:
$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=Whosebug");
$json1 = json_decode($surl,true);
print_r($json1);
当我尝试在 json_decode
之前 echo
$surl
的内容时,我得到一个充满 �
个字符的奇怪响应。
任何正确方向的提示都将不胜感激。
API 调用返回的字符串,according to the Stack Exchange API documentation 已被压缩。
Additionally, all API responses are compressed. The Content-Encoding header is always set, but some proxies will strip this out. The proper way to decode API responses can be found here.
您需要先使用 gzdecode()
解压缩字符串,然后您就可以正确地 json_decode()
它。
$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=Whosebug");
// Decode the compressed string
$surl = gzdecode($surl);
// Then you'll be able to json_decode() it...
$json1 = json_decode($surl, true);
print_r($json1);
// Prints:
Array
(
[items] => Array
(
[0] => Array
(
[tags] => Array
(
[0] => research
)
[owner] => Array
(
[reputation] => 9995
[user_id] => 1944
[user_type] => registered
[accept_rate] => 93
[profile_image] => https://www.gravatar.com/avatar/93fc84c261cdce2e2f1d64c8e531ecb7?s=128&d=identicon&r=PG
[display_name] => Charles Roper
我讨厌问这种问题,因为我知道答案一定非常简单,但我似乎想不出来。
我正在尝试解析来自 Stack Exchange API
的 JSON 响应,但结果是我得到一个空字符串,即使我检查了 URL 和 JSON 格式化,一切似乎都有效。
我使用的代码很简单:
$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=Whosebug");
$json1 = json_decode($surl,true);
print_r($json1);
当我尝试在 json_decode
之前 echo
$surl
的内容时,我得到一个充满 �
个字符的奇怪响应。
任何正确方向的提示都将不胜感激。
API 调用返回的字符串,according to the Stack Exchange API documentation 已被压缩。
Additionally, all API responses are compressed. The Content-Encoding header is always set, but some proxies will strip this out. The proper way to decode API responses can be found here.
您需要先使用 gzdecode()
解压缩字符串,然后您就可以正确地 json_decode()
它。
$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=Whosebug");
// Decode the compressed string
$surl = gzdecode($surl);
// Then you'll be able to json_decode() it...
$json1 = json_decode($surl, true);
print_r($json1);
// Prints:
Array
(
[items] => Array
(
[0] => Array
(
[tags] => Array
(
[0] => research
)
[owner] => Array
(
[reputation] => 9995
[user_id] => 1944
[user_type] => registered
[accept_rate] => 93
[profile_image] => https://www.gravatar.com/avatar/93fc84c261cdce2e2f1d64c8e531ecb7?s=128&d=identicon&r=PG
[display_name] => Charles Roper