我有一个返回JSON对象的URL,如下所示:
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
我想从URL中获取JSON对象,然后获取access_token
的值。
那么我如何通过PHP检索它呢?
发布于 2013-03-25 22:33:30
$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
来获取url。要使用curl,可以使用示例here
$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;
发布于 2013-03-25 22:35:28
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Php还可以使用带有破折号的属性:
garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
public $qwert-y =>
int(123)
}
=> null
发布于 2013-03-25 22:36:33
你可以使用PHP的json_decode函数:
$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
https://stackoverflow.com/questions/15617512
复制相似问题