JSON-object ophalen van URL

Ik heb een URL die een JSON-object als volgt retourneert:

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

Ik wil het JSON-object van de URL halen en vervolgens de waarde access_token.

Dus hoe kan ik het via PHP ophalen?


Antwoord 1, autoriteit 100%

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

Om dit te laten werken, vereist file_get_contentsdat allow_url_fopenis ingeschakeld. Dit kan tijdens runtime worden gedaan door het volgende op te nemen:

ini_set("allow_url_fopen", 1);

Je kunt ook curlom de url te krijgen. Om curl te gebruiken, kun je het voorbeeld gebruiken dat hier:

gevonden wordt

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

Antwoord 2, autoriteit 7%

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

Php kan ook eigenschappen met streepjes gebruiken:

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

Antwoord 3, autoriteit 5%

Je zou de json_decodefunctie van PHP kunnen gebruiken:

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

Antwoord 4, autoriteit 2%

Je moet lezen over de json_decode-functie http://php.net/manual /en/function.json-decode.php

Hier ga je

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

Antwoord 5, autoriteit 2%

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

Antwoord 6

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

Antwoord 7

file_get_contents()haalt de gegevens niet van url, daarna heb ik curlgeprobeerd en het werkt prima.


Antwoord 8

mijn oplossing werkt alleen voor de volgende gevallen:
als u een multidimensionale array verwart met één enkele

$json = file_get_contents('url_json'); //get the json
$objhigher=json_decode($json); //converts to an object
$objlower = $objhigher[0]; // if the json response its 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

ik weet dat het antwoord al is beantwoord, maar voor degenen die hier op zoek zijn naar iets, ik hoop dat dit je kan helpen


Antwoord 9

Als je curlgebruikt, krijg je soms 403 (toegang verboden)
Opgelost door deze regel toe te voegen om de browser te emuleren.

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

Ik hoop dat dit iemand helpt.


Antwoord 10

Onze oplossing, het toevoegen van enkele validaties aan het antwoord, zodat we er zeker van zijn dat we een goed gevormd json-object hebben in de $jsonvariabele

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

Antwoord 11

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

Je krijgt misschien 405, stel het methodetype correct in.

Other episodes