一尘不染

从URL获取JSON对象

php

我有一个网址,返回的是这样的JSON对象:

{
    "expires_in":5180976,
    "access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}

我想获得access_token价值。那么如何通过PHP检索它呢?


阅读 235

收藏
2020-05-26

共1个答案

一尘不染

$json = file_get_contents(‘url_here’);
$obj = json_decode($json);
echo $obj->access_token;

为此,file_get_contents需要allow_url_fopen启用它。可以通过在运行时完成以下操作来实现:

ini_set("allow_url_fopen", 1);

您也可以使用curl获取网址。要使用卷曲,可以使用中发现的例子在这里:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;
2020-05-26