【发布时间】:2014-07-02 18:08:04
【问题描述】:
这部分:
$response_2 = json_decode($response_2, true);
...下面的代码在浏览器中的字面意思是“数组”。如果我删除该部分,完整的 $response_2 将以 JSON 格式在浏览器中回显,就像在此示例中一样:https://developer.spotify.com/web-api/get-list-users-playlists/
怎么会?
<?php
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';
$credentials = "hidden:hidden";
$headers = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Basic " . base64_encode($credentials));
$data = 'grant_type=client_credentials';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
$token = $response['access_token'];
echo "My token is: " . $token;
$headers_2 = array(
"Accept: */*",
"Content-Type: application/x-www-form-urlencoded",
('Authorization: Bearer ' . $token));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.spotify.com/v1/users/wizzler/playlists');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_2);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response_2 = curl_exec($ch);
curl_close($ch);
$response_2 = json_decode($response_2, true);
echo $response_2;
?>
【问题讨论】:
-
json_decode()返回一个数组。你不能回显一个数组。使用print_r()或var_dump()检查内容。然后回显一个特定元素,如下所示:echo $response_2['foo'];. -
感谢!我选择了
print_r ($response_2);,效果很好。 -
酷。但是请注意,
print_r()仅用于调试;它并不打算在实际代码中使用。 @Rawland -
知道了!再次感谢。
-
您需要使用
foreach循环遍历数组。