programing

json_decode를 사용하여 PHP에서 JSON 개체를 구문 분석하는 중

bestprogram 2023. 3. 8. 21:56

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",
            ... },

          ... ]
        }
    }
}

이것은 동작하고 있는 것 같습니다.

$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로 설정하면 배열을 얻을 수 있으므로 -> 구문을 사용할 수 없습니다.또한 생성된 json 문서를 Firefox의 XML 구조를 표시하는 방법과 유사한 멋진 형식의 트리 뷰로 볼 수 있도록 JSONview Firefox 확장을 설치하는 것이 좋습니다.이렇게 하면 일이 훨씬 쉬워집니다.

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

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

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

이 예시를 사용해 보세요.

$json = '{"foo-bar": 12345}';

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

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

NB - 두 개의 음이 양의 값을 만듭니다. : )

["value"]를 잊어버린 것 같습니다.->value:

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

json을 디코딩할 때 객체 대신 배열을 반환하도록 강제합니다.

$data = json_decode($json, TRUE); -> // TRUE

그러면 어레이가 반환되고 키를 입력하여 값에 액세스할 수 있습니다.

먼저 서버가 원격 연결을 허용하는지 확인해야 합니다. 그러면 이 기능이file_get_contents($url)는 정상적으로 동작합니다.대부분의 서버는 보안상의 이유로 이 기능을 디세블로 합니다.

코드를 편집하면서(온화한 강박장애이기 때문에) 날씨도 리스트라는 것을 알게 되었습니다.아마 이런 걸 고려해봐야 할 거야

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

올바른 날짜 인스턴스에 weatherIconUrl을 사용하고 있는지 확인합니다.

언급URL : https://stackoverflow.com/questions/4035742/parsing-json-object-in-php-using-json-decode