'2018/05/18'에 해당되는 글 1건

728x90

[
    {
    "userID": 1383458400,
    "icon": "partly-cloudy-day",
    "sunriseTime": 1383491266,
    "sunsetTime": 1383523844,
    "temperatureMin": -3.46,
    "temperatureMinTime": 1383544800,
    "temperatureMax": -1.12,
    "temperatureMaxTime": 1383458400
    },
    {
    "userID": 1383458400,
    "icon": "partly-cloudy-day",
    "sunriseTime": 1383491266,
    "sunsetTime": 1383523844,
    "temperatureMin": -3.46,
    "temperatureMinTime": 1383544800,
    "temperatureMax": -1.12,
    "temperatureMaxTime": 1383458400
    }
] 



<?php
// Local JSON 파일 읽어오기

$url ='test.json';

if(!file_exists($url)) {
    echo '파일이 없습니다.';
    exit;
}

$json_string = file_get_contents($url);
$R = json_decode($json_string, true);
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.
// $R : array data
echo '<pre>';
print_r($R);
echo '</pre>';


// 자료 파싱처리

foreach ($R as $key => $value) {
    if (!is_array($value)) {
        echo $key . '=>' . $value . '<br/>';
    } else {
        foreach ($value as $key => $val) {
            echo $key . '=>' . $val . '<br/>';
        }
        echo '<br />';
    }
}
?>


위의 코드의 경우에는 이중 배열이므로 간단하게

foreach ($R as $row) {
    $userID= $row['userID'];
    $sunriseTime = $row['sunriseTime'];
}
로 원하는 데이터를 뽑아서 처리하면 된다.



JSON 데이터 형식이 다음과 같을 때

 { "Sample_Data" :
  [{
    "userID": 1383458400,
    "icon": "partly-cloudy-day",
    "sunriseTime": 1383491266,
    "sunsetTime": 1383523844,
    "temperatureMin": -3.46,
    "temperatureMinTime": 1383544800,
    "temperatureMax": -1.12,
    "temperatureMaxTime": 1383458400
    },
    {
    "userID": 1383458400,
    "icon": "partly-cloudy-day",
    "sunriseTime": 1383491266,
    "sunsetTime": 1383523844,
    "temperatureMin": -3.46,
    "temperatureMinTime": 1383544800,
    "temperatureMax": -1.12,
    "temperatureMaxTime": 1383458400
  }]
}


foreach ($R['Sample_Data'] as $row) {
    echo '<pre>'; print_r($row);echo '</pre>';
    echo $userID= $row['userID'].'<br />';
    echo $sunriseTime = $row['sunriseTime'].'<br />';
}


로 처리하면 해결된다.

'Web 프로그램 > JSON, 파싱 다루기' 카테고리의 다른 글

jQuery 파싱 예제  (0) 2018.12.16
PHP json_encode  (0) 2018.06.19
네이버 동네 날씨정보 파싱  (0) 2017.12.24
기상청 지역 날씨정보 파싱  (0) 2017.12.23
Parse JSON with PHP (JSON 파싱)  (2) 2017.11.27
블로그 이미지

Link2Me

,