developer tip

PHP를 사용하여 JSON 파일에서 데이터 가져 오기

copycodes 2020. 8. 17. 09:13
반응형

PHP를 사용하여 JSON 파일에서 데이터 가져 오기


이 질문에 이미 답변이 있습니다.

PHP를 사용하여 다음 JSON 파일에서 데이터를 가져 오려고합니다. 저는 특별히 "temperatureMin"과 "temperatureMax"를 원합니다.

정말 간단 할 수도 있지만 어떻게해야할지 모르겠습니다. 나는 file_get_contents ( "file.json") 후에 무엇을 해야할지 고민하고 있습니다. 도움을 주시면 대단히 감사하겠습니다!

{
    "daily": {
        "summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
        "icon": "clear-day",
        "data": [
            {
                "time": 1383458400,
                "summary": "Mostly cloudy throughout the day.",
                "icon": "partly-cloudy-day",
                "sunriseTime": 1383491266,
                "sunsetTime": 1383523844,
                "temperatureMin": -3.46,
                "temperatureMinTime": 1383544800,
                "temperatureMax": -1.12,
                "temperatureMaxTime": 1383458400,
            }
        ]
    }
}

다음을 사용하여 JSON 파일의 내용을 가져옵니다 file_get_contents().

$str = file_get_contents('http://example.com/example.json/');

이제 다음을 사용하여 JSON을 디코딩합니다 json_decode().

$json = json_decode($str, true); // decode the JSON into an associative array

모든 정보를 포함하는 연관 배열이 있습니다. 필요한 값에 액세스하는 방법을 알아 보려면 다음을 수행하십시오.

echo '<pre>' . print_r($json, true) . '</pre>';

이것은 읽기 쉬운 형식으로 배열의 내용을 출력합니다. 두 번째 매개 변수는 출력이 화면에 인쇄되는 것이 아니라 반환 되어야 함 true을 알리기 위해로 설정됩니다 . 그런 다음 다음과 같이 원하는 요소에 액세스합니다.print_r()

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

또는 원하는대로 배열을 반복합니다.

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

데모!


json_decode사용 하여 JSON을 PHP 배열로 변환합니다. 예:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

Try:
$data = file_get_contents ("file.json");
        $json = json_decode($data, true);
        foreach ($json as $key => $value) {
            if (!is_array($value)) {
                echo $key . '=>' . $value . '<br/>';
            } else {
                foreach ($value as $key => $val) {
                    echo $key . '=>' . $val . '<br/>';
                }
            }
        }

참고 URL : https://stackoverflow.com/questions/19758954/get-data-from-json-file-with-php

반응형