问题描述:
我有一个URL,返回一个JSON对象像这样:{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
我想从URL获取JSON对象,然后获取access_token值。
我如何通过PHP获取它?
回答:
方法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);
方法:2:
可以使用curl来获取url$ch = curl_init();
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;