Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从响应url提取令牌-Spotify API_Php_Api_Curl_Token_Spotify - Fatal编程技术网

Php 从响应url提取令牌-Spotify API

Php 从响应url提取令牌-Spotify API,php,api,curl,token,spotify,Php,Api,Curl,Token,Spotify,我使用以下代码从Spotify的Web API获取令牌: <?php $url = 'https://accounts.spotify.com/api/token'; $method = 'POST'; $credentials = "{Client ID}:{Client Secret}"; $headers = array( "Accept: */*", "Content-Type: application/x-www-form-urlencoded

我使用以下代码从Spotify的Web API获取令牌:

<?php
$url = 'https://accounts.spotify.com/api/token';
$method = 'POST';

$credentials = "{Client ID}:{Client Secret}";

$headers = array(
        "Accept: */*",
        "Content-Type: application/x-www-form-urlencoded",
        "User-Agent: runscope/0.1",
        "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);

$response = curl_exec($ch);
?>
太好了!但是,如何从响应中提取“{token}”,并将其用作API请求中的参数?例如,在对{user_id}/playlists的请求中,需要在标头字段中使用令牌


谢谢

您需要解码JSON:

$response = json_decode($response, true);
然后您将得到一个包含这些值的数组

$token = $response['access_token'];
此外,您还缺少通过这种方式获得响应的必要选项:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

如果未定义,您将得到一个布尔值,而不是响应。

我在最底部添加了这两行,然后将“echo$token;”放在后面,以验证“$token”是我想要的值,但它不会显示在我的浏览器中。我做错了什么?谢谢Do
var\u dump($response)
json\u decode
之前和之后。很抱歉,我不能正确理解。我真的不需要在浏览器中显示令牌值。我想从响应中提取{token},并在调用API时将其用作值。我应该把你的两行原始代码放在我的代码中的什么地方,如何验证它是否正常工作?你能把你的代码行放到我的代码里吗?谢谢
var_dump
仅用于调试代码并验证其是否正常工作。答案的两行应该放在
$response=curl\u exec($ch)后面你在
var_dump
中看到了什么?下面是我添加行时的代码:它给出的结果与原始问题中提到的相同,但后面有bool(true)int(1)。
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);