【问题标题】:How can I get part of a JSON response that is returned from a curl POST using PHP如何获取使用 PHP 从 curl POST 返回的 JSON 响应的一部分
【发布时间】:2020-11-11 19:25:27
【问题描述】:

我发布到 API 以获取授权令牌。问题是这个令牌只激活了 24 小时,所以我正在创建一个每 24 小时获取一个新令牌的 cronjob。

这是我使用 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>';
?>

这会返回:

{
"payload": "{\"access_token\":\"my_auth_token\",\"expires_in\":86400,\"token_type\":\"Bearer\"}"
}

我怎样才能得到access_token 作为唯一的输出?我试过回显有效载荷,但我不知道该怎么做。

echo $result[0]->payload;

echo $result->payload;

两者都不起作用。

【问题讨论】:

  • 尝试$result['payload']返回一个json字符串,然后解析它。
  • @Gavin 打印或回显仅返回 {

标签: php json api curl post


【解决方案1】:

你忘记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));

Please take a look at playground

【讨论】:

    【解决方案2】:

    您似乎从 curl 请求中获得了 JSON 响应。

    使用代码中的虚拟参数我无法对其进行测试,但我想解决方案是这样的:

    <?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;
    ?>
    

    让我知道它是否有效。

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 2012-03-08
      • 2014-03-10
      • 2023-01-29
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多