从URL获取JSON对象

175

我有一个URL,它返回一个像这样的JSON对象:

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

我想从URL获取JSON对象,然后获取access_token的值。

那么我该如何通过PHP检索它?


2
json_decode($your_string) 应该就可以了。 - d4rkpr1nc3
请查看https://dev59.com/w2855IYBdhLWcg3wbzxl。 - ophintor
11个回答

408
$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,你可以使用在这里找到的示例:

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

1
如果您想将结果用作数组,请在json_decode函数中使用", true"。请参考我的答案。 - netblognet
file_get_contents('url'); 这里有一个与此相关的错误。 - user2199343
那是另一个问题,你应该开一个新的问题来问。 - Prisoner
现在已经修复了。我刚刚从我的领英帐户重新登录。感谢您的协助。 - user2199343
1
你可以在运行时使用 ini_set("allow_url_fopen", 1);allow_url_fopen 设置为启用。 - Cԃաԃ
显示剩余7条评论

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

1
我只因为一个原因更喜欢这个答案,那就是解析的JSON可能包含带破折号的索引。 例如:{"full-name":"khalil","familiy-name":"whatever"}。 将其解码为数组将让你处于安全的一面。 - Khalil Awada

22
您可以使用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"];

好的例子,但方法应该被称为 json_decode 而不是 $json_decode - czerasz

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

1
请使用代码块格式化代码,并添加解释性注释,特别是当代码不能直接回答问题时(在这种情况下,可能存在不同的键名等)。 - elliot42
这是从哪里复制来的?源头在哪里?看起来像是随意搜索问题,盲目地将第一个搜索结果粘贴作为答案。 - Peter Mortensen

8

你需要了解关于 json_decode 函数的内容。

这里是相关资料:

$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']);

2
$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;

3
欢迎来到StackOverflow!这个问题已经被回答了多次!请详细说明您的答案与其他答案的不同之处,并改进它们,而不是简单地倾倒一些代码。 - T3 H40

2

file_get_contents() 无法从 URL 获取数据。然后我尝试了 curl,它可以正常工作。


1

我的解决方案仅适用于以下情况:

如果您将多维数组误认为是单一数组:

$json = file_get_contents('url_json'); // Get the JSON content
$objhigher=json_decode($json); // Cconverts to an object
$objlower = $objhigher[0]; // If the JSON response is multidimensional, this lowers it
echo "<pre>"; // Box for code
print_r($objlower); // Prints the object with all key and values
echo $objlower->access_token; // Prints the variable

1

我们的解决方案是在响应中添加一些验证,以确保我们在$json变量中拥有格式良好的JSON对象:

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
    return false;
}

$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
    return false;
}

0
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
//Set the GET method by giving 0 value and for POST set as 1
//curl_setopt($curl_handle, CURLOPT_POST, 0);
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
$query = curl_exec($curl_handle);
$data = json_decode($query, true);
curl_close($curl_handle);

//print complete object, just echo the variable not work so you need to use print_r to show the result
echo print_r( $data);
//at first layer
echo $data["tradedDate"];
//Inside the second layer
echo $data["data"][0]["companyName"];

有时候你可能会得到405错误,需要正确设置请求方法类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接