Подтвердить что ты не робот

Получить объект JSON из URL-адреса

У меня есть URL-адрес, который возвращает объект JSON следующим образом:

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

Я хочу получить значение access_token. Итак, как я могу получить его через PHP?

4b9b3361

Ответ 1

$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-адрес. Чтобы использовать завиток, вы можете использовать найденный пример здесь:

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

Ответ 2

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

Php также может использовать свойства с тире:

[email protected] ~/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

Ответ 3

Вы можете использовать функцию 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"];

Ответ 4

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

Ответ 5

Вам нужно прочитать о функции 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']);

Ответ 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;

Ответ 7

file_get_contents() не извлекает данные из url, тогда я пробовал curl и работал нормально.

Ответ 8

Когда вы используете curl иногда выдает 403 (доступ запрещен), решив, добавив эту строку для эмуляции браузера.

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

Надеюсь, это поможет кому-то.

Ответ 9

Наше решение, добавив некоторые проверки в ответ, поэтому мы уверены, что у нас есть правильно сформированный объект 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;
}

Ответ 10

мое решение работает только для следующих случаев: если вы ошибочно принимаете многомерный массив в единый

$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

я знаю, что ответ был уже дан ответ, но для тех, кто пришел сюда в поисках чего-то, я надеюсь, что это может помочь вам