【问题标题】:JSON decode shows "Array"JSON 解码显示“数组”
【发布时间】: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 循环遍历数组。

标签: php json curl encode


【解决方案1】:

当您在数组上使用echo 时,它只会打印出文字字符串Array。这只是 PHP 的一个怪癖。

如果要打印出数组的内容,可以使用print_r()var_dump()

但是,您实际上想要做的是打印 JSON,即字符串。 $response_2 已经是字符串了,打印出来吧。

【讨论】:

猜你喜欢
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 2016-04-19
  • 1970-01-01
  • 2016-06-08
相关资源
最近更新 更多