728x90

네이버 지식인에 문의된 대구와 부산의 날씨 정보 파싱 예제다.


<?php
include_once 'simple_html_dom.php';

$url = "https://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT001024"; // 용인
$url1 = "https://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT007007"; // 대구
$url2 = "https://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT008008"; // 부산

$R = weather_parse($url1);
$S = weather_parse($url2);
echo json_encode(array("Time1"=>$R[0], "Weather1"=>$R[1],"Finedust1"=>$R[2],"Time2"=>$S[0], "Weather2"=>$S[1],"Finedust2"=>$S[2])); // 대구와 부산 날씨 정보

function weather_parse($url){
    $str = file_get_contents_curl($url);
    $enc = mb_detect_encoding($str, array('EUC-KR', 'UTF-8', 'shift_jis', 'CN-GB'));
    if ($enc != 'UTF-8') {
        $str = iconv($enc, 'UTF-8', $str);
    }

    $html = new simple_html_dom(); // Create a DOM object
    $html->load($str); // Load HTML from a string

    $R = array();
    $item = $html->find('div[class=c_tit2]',0)->find('em',0)->plaintext;
    array_push($R,$item);
    $item = $html->find('div[class=w_now2]',0)->find('em',0)->plaintext;
    array_push($R,$item);
    $item = $html->find('div[class=w_now2]',0)->find('em',1)->plaintext;
    array_push($R,$item);
    return $R;
}

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);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // https 일때 이 한줄 추가 필요
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
?>


파일에 대한 설명은 https://link2me.tistory.com/1603 참조하라.


블로그 이미지

Link2Me

,