我有一个返回JSON对象的URL,如下所示:
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
Run Code Online (Sandbox Code Playgroud)
我想得到access_token价值.那我怎么能通过PHP检索呢?
Pri*_*ner 339
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
Run Code Online (Sandbox Code Playgroud)
为此,file_get_contents要求allow_url_fopen已启用.这可以在运行时通过包括:
ini_set("allow_url_fopen", 1);
Run Code Online (Sandbox Code Playgroud)
您还可以使用curl获取网址.要使用curl,您可以使用此处的示例:
$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;
Run Code Online (Sandbox Code Playgroud)
gaR*_*Rex 26
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
net*_*net 17
你可以使用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"];
Run Code Online (Sandbox Code Playgroud)
小智 8
// Get the string from the URL
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
// Decode the JSON string into an object
$obj = json_decode($json);
// In the case of this input, do key and array lookups to get the values
var_dump($obj->results[0]->formatted_address);
Run Code Online (Sandbox Code Playgroud)
你需要阅读json_decode函数http://php.net/manual/en/function.json-decode.php
干得好
$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');
$obj = json_decode($json);
var_dump($obj-> access_token);
//OR
$arr = json_decode($json, true);
var_dump($arr['access_token']);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
439057 次 |
| 最近记录: |