URL에서 JSON 객체 가져 오기
다음과 같이 JSON 객체를 반환하는 URL이 있습니다.
{
"expires_in":5180976,
"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
}
나는 access_token
가치 를 얻고 싶다 . PHP를 통해 어떻게 검색 할 수 있습니까?
$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();
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;
$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
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 함수 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']);
// 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);
$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;
file_get_contents()
URL에서 데이터를 가져 오지 않고 시도했지만 curl
제대로 작동합니다.
내 솔루션은 다음 경우에만 작동합니다. 다차원 배열을 단일 배열로 착각하는 경우
$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
i know that the answer was has already been answered but for those who came here looking for something i hope this can help you
When you are using curl
sometimes give you 403 (access forbidden) Solved by adding this line to emulate 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)');
Hope this help someone.
Our solution, adding some validations to response so we are sure we have a well formed json object in $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;
}
참고URL : https://stackoverflow.com/questions/15617512/get-json-object-from-url
'Programing' 카테고리의 다른 글
최고의 오픈 소스 Java 차트 라이브러리는 무엇입니까? (0) | 2020.06.30 |
---|---|
ES6 모듈의 수입을 조롱하는 방법? (0) | 2020.06.30 |
하나 이상의 공백 또는 탭으로 문자열 분해 (0) | 2020.06.29 |
EF Core를 사용하여 ASP.NET Core에서 마이그레이션을 적용 취소하는 방법 (0) | 2020.06.29 |
lodash를 사용하여 Array에서 객체를 찾아 반환하는 방법은 무엇입니까? (0) | 2020.06.29 |