175

I have a URL that returns a JSON object like this:

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

I want to get JSON object from the URL and then the access_token value.

So how can I retrieve it through PHP?

Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
user2199343
  • 1,883
  • 3
  • 13
  • 9

11 Answers11

408
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

For this to work, file_get_contents requires that allow_url_fopen is enabled. This can be done at runtime by including:

ini_set("allow_url_fopen", 1);

You can also use curl to get the URL. To use curl, you can use the example found 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;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Prisoner
  • 27,391
  • 11
  • 73
  • 102
  • Sorry I forgot to mention that first how do I get this string from the url then access the json object? – user2199343 Mar 25 '13 at 14:35
  • The error came on this line echo $obj['access_token']; Fatal error: Cannot use object of type stdClass as array in F:\wamp\www\sandbox\linkedin\test.php on line 22 – user2199343 Mar 25 '13 at 14:39
  • 1
    @user2199343 If you want to use the result as array, use ", true" in json_decode function. See my answer for example. – netblognet Mar 25 '13 at 14:41
  • file_get_contents('url'); There is an error referring to this – user2199343 Mar 25 '13 at 14:53
  • Warning: file_get_contents(https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=AQSuFANDoXm9OkKT3oH_1ReZ0CZVJGuG5rBncJVWR8QRHihxlDryCTs7oiWN3BViVJJn_QIg7AzMp4cXz98F_9CV0jIkNHoEDMb7pUcO2OYKGb5Bchg&redirect_uri=http://127.0.0.1:8088/sandbox/linkedin/test.php&client_id=1ba8ogpm9e05&client_secret=n7GN09I3F2L3IJD1) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in F:\wamp\www\sandbox\linkedin\test.php on line 20 – user2199343 Mar 25 '13 at 14:54
  • That's a different issue, you should open up another question for it. – Prisoner Mar 25 '13 at 14:57
  • It's now fixed. I just logged in again from my linkedin account. Thank you for the asisstance. – user2199343 Mar 25 '13 at 16:48
  • 1
    you can put this line at the top `ini_set("allow_url_fopen", 1);` to enable `allow_url_fopen` at runtime. – Cԃաԃ Jun 15 '15 at 06:37
  • Curl complete example: http://stackoverflow.com/questions/16700960/how-to-use-curl-to-get-json-data-and-decode-the-data?answertab=active#tab-top – Web_Developer Jan 08 '16 at 11:49
  • @Web_Developer i will add this to the post – Prisoner Jan 08 '16 at 11:52
  • does curl not need allow_url_fopen enabled? Or both of them do need it? – Ruben Marrero Feb 23 '17 at 11:06
  • [You should not switch off `CURLOPT_SSL_VERIFYHOST` or `CURLOPT_SSL_VERIFYPEER`](https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software). It could be a security risk! [Here is how to get the certificate bundle if your server is missing one](https://stackoverflow.com/a/32095378/1839439) – Dharman Jun 07 '19 at 16:34
28
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];

PHP also can use properties with dashes:

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gaRex
  • 4,144
  • 25
  • 37
  • 1
    i would prefer this answer on the chosen answer for 1 reason only the parsed json could contain index with dash character ex: {"full-name":"khalil","familiy-name":"whatever"} decoding as array will keep you on the safe side – Khalil Awada May 14 '15 at 08:11
22

You could use PHP's json_decode function:

$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];
netblognet
  • 1,951
  • 2
  • 20
  • 46
8

You need to read about the json_decode function.

Here you go:

$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']);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick
  • 602
  • 9
  • 22
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);
elliot42
  • 3,694
  • 3
  • 26
  • 27
Toqeer Ahmed
  • 81
  • 1
  • 1
  • 1
    Prefer code block formatting for code, and explanatory comments, especially if the code doesn't specifically answer the question directly (in this case there are different key names etc.) – elliot42 Nov 19 '15 at 23:21
  • Where has this been copied from? What is the source? It looks like drive by, google the question, and blindly paste the first search result as an answer. – Peter Mortensen Mar 18 '23 at 14:18
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;
Ya-Ze Lin
  • 29
  • 2
  • 3
    Welcome to StackOverflow! This question has already been answered multiple times! Please elaborate on how your answer is different and improves the others, instead of simply dumping some code. – T3 H40 Jan 11 '16 at 07:50
2

file_get_contents() was not fetching the data from a URL. Then I tried curl and it was working fine.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Firdous bhat
  • 105
  • 7
1

Our solution, adding some validations to response, so we are sure we have a well-formed JSON object in the $json variable:

$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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raul Sanchez
  • 270
  • 2
  • 17
1

My solution only works for the following cases:

If you are mistaking a multidimensional array into a single one:

$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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

When you are using curl, it sometimes gives you a 403 (access forbidden).

I solved by adding this line to emulate a browser.

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dev strange
  • 138
  • 1
  • 2
  • 10
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"];

Some time you might get 405, set the method type correctly.

YB Idea
  • 1
  • 1
  • 1