Coder Perfect

Retrieve a JSON object from a URL


I’ve got a URL that produces a JSON object, which looks like this:


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

So, how can I get it back using PHP?

Asked by user2199343

Solution #1

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

Allow url fopen must be enabled for file get contents to function. This can be accomplished during runtime by including the following:

ini_set("allow_url_fopen", 1);

Curl can also be used to obtain the url. You can use the following example to learn how to use curl:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read
// 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);

$obj = json_decode($result);
echo $obj->access_token;

Answered by Prisoner

Solution #2

$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];

Properties with dashes can also be used in 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 =>
=> null

Answered by gaRex

Solution #3

You might use PHP’s json decode function to accomplish this:

$url = "";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];

Answered by netblognet

Solution #4 is a good place to start learning 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('');

$obj = json_decode($json);
var_dump($obj-> access_token);


$arr = json_decode($json, true);

Answered by Nick

Solution #5

// Get the string from the URL
$json = file_get_contents(',-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

Answered by Toqeer Ahmed

Post is based on