728x90

네이버에서 제공하는 날씨 정보를 파싱하는 방법이다.


<?php
$url = 'http://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT001024#nhn_weather_tab';

function file_get_contents_curl($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$html = file_get_contents_curl($url);

// 가져온 데이터가 깨져보이는 경우는 인코딩 모드가 UTF-8 이 아닐 수 있다.
$enc = mb_detect_encoding($html, array('EUC-KR', 'UTF-8', 'shift_jis', 'CN-GB'));
if ($enc != 'UTF-8') {
    $html = iconv($enc, 'UTF-8', $html);
}
print_r($html);
?>


위와 같이 cURL 을 이용하면 해당 페이지 정보가 보이는데 XML이 아니라 HTML Web 이다.

소스보기를 하면 html 코드들이 보인다.


PHP Simple HTML DOM Parser 를 이용하면 원하는 곳만 쉽게 뽑아낼 수 있다.

http://simplehtmldom.sourceforge.net/ 에 가면 다운로드 받을 수 있다.

jQuery 처럼 selector 로 HTML 페이지에 있는 tags를 찾을 수 있다.


PHP Simple HTML DOM Parser 로 가져온 걸 echo 로 찍어보면 한줄로 보여서 가독성이 떨어진다.

그래서 cURL 로 가져와서 소스보기를 한 다음 원하는 태그를 find로 찾아서 원하는 결과를 출력하면 된다.

http://simplehtmldom.sourceforge.net/manual.htm 매뉴얼에 좀 더 상세한 사용법 예제들이 나온다.


<?php
$url = 'http://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT001024#nhn_weather_tab';

include_once 'simple_html_dom.php';
$html = file_get_html($url);

//echo $html->find('li[id="tab_CT001000"]',0);
echo $html->find('div[id="content_sub"]',0)->children(0);
//echo $html->find('div[id="content_sub"]',0)->children(1);
echo $html->find('div[class="w_now2"]',0)->children(0)->children(0)->children(0);

echo $html->find('div[class="fl"]',0);
echo $html->find('div[class="fl"]',0)->plaintext;

//echo $html->find('div[class="fl"]',0)->children(0);
//echo $html->find('div[class="fl"]',0)->children(1);
//echo $html->find('div[class="fl"]',0)->children(2);
?>
 


위 박스에 나온 예제를 소스보기로 비교하면서 실행해보면 금방 이해된다.

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

PHP json_encode  (0) 2018.06.19
PHP Local JSON 파일 읽어오기  (0) 2018.05.18
기상청 지역 날씨정보 파싱  (0) 2017.12.23
Parse JSON with PHP (JSON 파싱)  (2) 2017.11.27
PHP Array 활용 JSON  (0) 2017.05.11
블로그 이미지

Link2Me

,