복붙노트

json_decode를 사용하여 PHP에서 JSON 객체 파싱하기

PHP

json_decode를 사용하여 PHP에서 JSON 객체 파싱하기

JSON 형식으로 데이터를 제공하는 웹 서비스에서 날씨를 요청하려고했습니다. 내 PHP 요청 코드는 성공하지 못했습니다 :

$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;    

이것은 반환 된 일부 데이터입니다. 간결성을 위해 일부 세부 사항이 생략되었지만 개체 무결성이 유지됩니다.

{ "data": 
    { "current_condition": 
        [ { "cloudcover": "31",
            ... } ],  
      "request": 
        [ { "query": "Schruns, Austria",
            "type": "City" } ],
      "weather": 
        [ { "date": "2010-10-27",
            "precipMM": "0.0",
            "tempMaxC": "3",
            "tempMaxF": "38",
            "tempMinC": "-13",
            "tempMinF": "9",
            "weatherCode": "113",
            "weatherDesc": [ {"value": "Sunny" } ],
            "weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
            "winddir16Point": "N",
            "winddirDegree": "356",
            "winddirection": "N",
            "windspeedKmph": "5",
            "windspeedMiles": "3" }, 
          { "date": "2010-10-28",
            ... },

          ... ]
        }
    }
}

해결법

  1. ==============================

    1.이 작동하는 것 같습니다.

    이 작동하는 것 같습니다.

    $url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
    $content = file_get_contents($url);
    $json = json_decode($content, true);
    
    foreach($json['data']['weather'] as $item) {
        print $item['date'];
        print ' - ';
        print $item['weatherDesc'][0]['value'];
        print ' - ';
        print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
        print '<br>';
    }
    

    json_decode의 두 번째 매개 변수를 true로 설정하면 배열이 생기므로 -> 구문을 사용할 수 없습니다. 또한 JSONview Firefox 확장을 설치하여 Firefox에서 XML 구조를 표시하는 방식과 유사한 멋진 형식의 트리보기에서 생성 된 json 문서를 볼 수 있습니다. 이것은 일을 훨씬 쉽게 만듭니다.

  2. ==============================

    2.다음을 대신 사용하는 경우 :

    다음을 대신 사용하는 경우 :

    $json = file_get_contents($url);
    $data = json_decode($json, TRUE);
    

    TRUE는 객체 대신 배열을 반환합니다.

  3. ==============================

    3.이 예제를 사용해보십시오.

    이 예제를 사용해보십시오.

    $json = '{"foo-bar": 12345}';
    
    $obj = json_decode($json);
    print $obj->{'foo-bar'}; // 12345
    

    http://php.net/manual/en/function.json-decode.php

    NB - 두 개의 음화가 양성입니다. :)

  4. ==============================

    4.[ "value"] 또는 -> 값을 잊어 버린 것 같습니다 :

    [ "value"] 또는 -> 값을 잊어 버린 것 같습니다 :

    echo $data[0]->weather->weatherIconUrl[0]->value;
    
  5. ==============================

    5.먼저 서버가 원격 연결을 허용하는지 확인하여 file_get_contents ($ url) 함수가 잘 작동하도록하고, 대부분의 서버는 보안상의 이유로이 기능을 사용하지 않도록 설정해야합니다.

    먼저 서버가 원격 연결을 허용하는지 확인하여 file_get_contents ($ url) 함수가 잘 작동하도록하고, 대부분의 서버는 보안상의 이유로이 기능을 사용하지 않도록 설정해야합니다.

  6. ==============================

    6.코드를 편집하는 동안 (온화한 강박 신경증 때문에), 나는 날씨도 목록이라는 것을 알아 차렸다. 아마도 다음과 같은 것을 고려해야합니다.

    코드를 편집하는 동안 (온화한 강박 신경증 때문에), 나는 날씨도 목록이라는 것을 알아 차렸다. 아마도 다음과 같은 것을 고려해야합니다.

    echo $data[0]->weather[0]->weatherIconUrl[0]->value;
    

    올바른 날짜 인스턴스에 weatherIconUrl을 사용하고 있는지 확인하십시오.

  7. from https://stackoverflow.com/questions/4035742/parsing-json-object-in-php-using-json-decode by cc-by-sa and MIT license