[英]How can I get part of a JSON response that is returned from a curl POST using PHP
I am posting to an API to get an authorization token.我发布到 API 以获取授权令牌。 The problem is this token is only activated for 24 hours so I am creating a cronjob that gets a new token every 24 hours.
问题是这个令牌只激活了 24 小时,所以我正在创建一个每 24 小时获取一个新令牌的 cronjob。
This is my post using CURL:这是我使用 CURL 的帖子:
<?PHP
// GET auth token
$url = 'https://website.nl';
$data = array("client_id" => "myclientid","client_secret" => "mysecret");
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r ($result);
echo '</pre>';
?>
This returns:这将返回:
{
"payload": "{\"access_token\":\"my_auth_token\",\"expires_in\":86400,\"token_type\":\"Bearer\"}"
}
How can I get access_token
as the only output?如何获得
access_token
作为唯一的 output? I've tried echoing payload but I am not sure how to do it.我试过回显有效载荷,但我不知道该怎么做。
echo $result[0]->payload;
echo $result->payload;
Both don't work.两者都不起作用。
You have forgotten to json_decode
你忘记了
json_decode
$url = 'https://jsonplaceholder.typicode.com/todos/1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
$result = curl_exec($ch);
curl_close($ch);
var_dump(json_decode($result));
looks like you're getting a JSON response from the curl request.看起来您从 curl 请求中获得了 JSON 响应。
With the dummy parameters in the code I could't test it, but I guess the solution would be something like this:使用代码中的虚拟参数我无法测试它,但我想解决方案是这样的:
<?PHP
// GET auth token
$url = 'https://website.nl';
$data = array("client_id" => "myclientid","client_secret" => "mysecret");
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode(stripslashes($response));
echo $result->payload->access_token;
?>
Let me know if it works.让我知道它是否有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.