728x90

juso.go.kr 사이트에 Python selenium 으로 조회하여 반환받은 결과를 DB에 넣고자 하는데 지번주소 세부주소까지 나오는 데이터가 있다.

 

이를 파싱처리는 코드를 PHP로 구현하고 적어둔다.

주소를 살펴보다 확인 결과 세종로 같은 경우가 빠져있다.

 

<?php
 
ini_set("display_startup_errors"1);
ini_set("display_errors"1);
error_reporting(E_ALL);
 
 
$address = '경기도 평택시 안중읍 안중리 산 69-7번지';
$address = '인천광역시 강화군 화도면 사기리 502-1번지';
$address = '경기도 부천시 소사구 괴안동 105-3 역곡현대아파트2차';
$address = '경기도 부천시 오정구 여월동 329 부천소방서 여월119안전센터';
 
preg_match('/(.+?)동\s/'$address,$out);
if(!empty($out&& strlen($out[0])>0) {
    $jusoDong = preg_replace("/\s{2,}/"," ",$out[0]);
    $str = explode($out[0],$address);
    $vout = explode(" ",$str[1]);
    $jiAddress = $jusoDong.' '.$vout[0];
    $jiAddress = preg_replace("/\s{2,}/"," ",$jiAddress);
    echo $jiAddress.'<br/>';
else {
    preg_match('/(.+?)가\s/'$address,$out);
    if(!empty($out&& strlen($out[0])>0) {
        $jusoDong = preg_replace("/\s{2,}/"," ",$out[0]);
        echo $jusoDong.'<br/>';        
    } else {
        preg_match('/(.+?)[읍,면]\s/'$address,$out);
        if(!empty($out&& strlen($out[0])>0) {
            $str = explode($out[0],$address);
            preg_match('/(.+?)리\s/'$str[1],$vout);
            if(!empty($vout&& strlen($vout[0])>0) {
                $jusoDong = trim($out[0].' '.$vout[0]);
                $jusoDong = preg_replace("/\s{2,}/"," ",$jusoDong);
                echo $jusoDong.'<br/>';
            } else {
                echo $address.'<br/>';
            }
            
        }
    }
 
?>
 

 

 

 

 

블로그 이미지

Link2Me

,
728x90

주소(juso.go.kr) 사이트에서 파일을 다운로드 받아서 주소를 만들고 파싱처리를 하다보니 이런 데이타가 있더라.

 

대부분은 지번주소가 존재하는데 신규로 생성되는 도로명주소에 해당하는 지번주소가 없는 것이다.

이런 데이터는 Naver Map API 에 위치좌표를 조회하면 결과가 없는 경우가 있다.

그렇다고 구글 Geocording API 를 연동하여 처리를 하자니 건당 비용이 발생해서 못하겠다.

불편하지만 구글 스프레드시트를 통해서 자료를 업데이트하는 수 밖에...

방법을 좀 더 찾아봐야겠다.

 

 

 

블로그 이미지

Link2Me

,
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

,
728x90

PHP Simple HTML DOM Parser 를 활용하여 네이버 날씨정보를 파싱하는 방법이다.


준비물

http://simplehtmldom.sourceforge.net/ 에서 파일을 다운로드하고 simple_html_dom.php 를 include 한다.

다운로드 받은 파일에 포함된 예제는 읽어보거나, 구글링해서 사용법에 대한 예제를 찾아보면 된다.


<?php
include_once 'simple_html_dom.php';
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 일때 이 한줄 추가 필요
    //Set curl to return the data instead of printing it to the browser.
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

?> 


그럼 2단계로 파싱할 곳을 선택한다.

내가 사는 지역인 용인지역을 파싱할 곳으로 선택하고, 네이버 날씨정보 URL을 알아낸다.


$url = "https://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT001024";


$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);
}

print_r($str);


여기까지 하면 날씨정보에 대한 소스보기를 할 수 있다.

마우스 우클릭하여 소스보기를 하면 소스 정보가 나온다.

소스에서 파싱할 곳을 찾아내야 한다.


소스보기에 아래 그림을 찾아낼 수 있다.

<em>태그안에 있는 정보가 파싱할 정보라는 걸 확인할 수 있다.


그럼 이제 simple_html_dom 파싱 처리를 위한 단계로 코드를 구현하자.

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


<em> 태그를 파싱하는 방법은 아래와 같이 하면 모든 em 태그를 찾아준다.

foreach($html->find('em') as $element){
    echo $element->innertext . '<br>';
}


시간정보만 파싱해보자.

foreach($html->find('div[class=c_tit2]',0)->find('em') as $element){
    echo $element->innertext . '<br>';
}
와 같이하면 시간정보만 파싱되는 걸 확인된다.

$html->find('div[class=c_tit2]',0) 와 같이 0을 넣어주어야 하는 거 잊지말자. 소스와 비교하여 확인하면 된다.

find는 선택한 태크를 찾고 그 자식들을 모두 찾는데 다시 find 로 em 태크를 선택한 것이다.

육안으로 확인하면 하나 밖에 없다는 것을 알 수 있으므로

$time = $html->find('div[class=c_tit2]',0)->find('em');

를 하면 Trying to get property of non-object라고 하면서 에러가 발생한다.

$item = $html->find('div[class=c_tit2]',0)->find('em',0); 라고 하면 에러가 발생하지 않는다.

echo $item->plaintext; 를 하면 시간 정보가 출력되는 걸 확인할 수 있다.

한번에 하면 $item = $html->find('div[class=c_tit2]',0)->find('em',0)->plaintext; 로 하면 된다.


원하는 결과만 뽑아내면

$R = array();
foreach($html->find('em') as $element){
    array_push($R,$element->innertext);
}
echo '시간 : '.$R[1].'<br />';
echo '날씨 : '.$R[2].'<br />';
echo '미세먼지 : '.$R[3].'<br />';


하나 하나 분리해서 코드를 작성해보면....

$item = $html->find('div[class=c_tit2]',0)->find('em',0)->plaintext;
echo $item.'<br />';

$item = $html->find('div[class=w_now2]',0)->find('em',0)->plaintext;
echo $item.'<br />';

$item = $html->find('div[class=w_now2]',0)->find('em',1)->plaintext;
echo $item.'<br />';


코드를 Android 에서 JSON 으로 파싱처리하도록 수정했다.

<?php
include_once 'simple_html_dom.php';
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 일때 이 한줄 추가 필요
    //Set curl to return the data instead of printing it to the browser.
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

$url = "https://weather.naver.com/rgn/cityWetrCity.nhn?cityRgnCd=CT001024";

$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);
}

//print_r($str);

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

$R = array();
foreach($html->find('em') as $element){
    array_push($R,$element->innertext);
}
$R[2] = preg_replace("(\<(/?[^\>]+)\>)", "", $R[2]); // html 태그를 없애는 정규식
echo json_encode(array("Time"=>$R[1], "Temperature"=>$R[2],"Fine dust"=>$R[3]));
?>


이렇게 하면 네이버 날씨정보 소스코드가 달라져도 이 PHP 파일만 수정해주면 되므로 Android 앱에서는 잘못된 정보로 업데이트할 일이 없을 것이다.


블로그 이미지

Link2Me

,
728x90

PHP 에서 배열 데이터를 json_encode 로 생각없이 넘겨주면 jQuery JSON 에서 처리를 쉽게 해결될 줄 알고 구글링하면서 이것 저것 찾아서 해결하면 금방 잊어버리고 그랬다.

분명히 예전에 했던 것인데 다시 할려고 하니까 시간을 또 허비하고 있다.

뭔가 대충해서 문제가 있는 거 같아서 집중적으로 테스트를 해봤다.


먼저 PHP에서 넘겨주는 데이터 파일을 보자.

 <?php
require_once 'path.php';
require_once $g['path_center'].'config/config.php';
require_once $g['path_class'].'connect.php';
require_once $g['path_class'].'dbDataClass.php';
$c = new DBDataClass;
$sql ="select idx,userNM,telNO,mobileNO,codeID FROM member ";
$sql.="where userID='".$_REQUEST['userID']."'";
$result = mysqli_query($db,$sql);
$R = array();
if($row = mysqli_fetch_assoc($result)):
    array_push($R,$row);
endif;

//echo '<pre>';print_r($R);echo '</pre>';
echo json_encode($R);
//echo json_encode(array('rs' => $R));
?>


보다시피 배열로 만들어진 결과를 json_encode 한 다음에 echo 문으로 출력을 한 것이다.


이제 클라이언트 JSON 처리 파일을 살펴보자.

결과 그림부터 보고 아래 코드를 살펴보면 뭐가 다른지 보인다.

문자열은 중괄호({})로 둘러쌓여 있는데, PHP에서 넘겨온 데이터는 대괄호([])가 있고 중괄호({})가 있는 형태다.

이렇게 데이터 형태가 다른데 이걸 JSON.parse 만 하면 원하는 object 로 되는 줄 알고 처리를 시도했더니 결과가 나오지 않았던 것이다.

이걸 stringify 하여 문자열로 변환한 다음에 split 으로 대괄호 부분을 제거하고 다시 JSON.parse 를 하면 원하는 결과가 나온다.

var obj = JSON.stringify(msg); // 문자열로 변경된다.
var objsplit1 = obj.split(']');
var objsplit2 = objsplit1[0].split('[');
var rs = JSON.parse(objsplit2[1]);
console.log('idx = '+rs.idx);


이렇게 처리하거나 배열로 뽑아내서 원하는 결과를 얻어서 처리하는 방법이 최선이다.

var arr= new Array();
$.each(msg, function(key, obj){
    $.each(obj,function(k,value){
        arr.push(value)
    });
});


<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>JSON Object, String</h2>
<p id="txt"></p>
<p id="obj_parse"></p>
<p id="obj"></p>
<p id="post_msg"></p>
<p id="ajax_msg"></p>
<p id="json2string"></p>
<p id="stringify"></p>
<script>
var txt = '{"name":"홍길동", "age":30, "city":"서울"}';
$('#txt').html('문자열 : '+txt);

var obj = JSON.parse(txt);
$("#obj_parse").html(obj.name + ", " + obj.age);

document.getElementById("obj").innerHTML = obj;
// $("#obj").html(obj); // 출력 결과물이 화면에 표시하지 못한다.

$.post('json.php',{userID:72771381},function(msg){
    console.log(msg); // 결과가 문자열로 넘어온다.
    //document.getElementById("post_msg").innerHTML = msg;
    $('#post_msg').html(msg);
});

$.ajax({
    url: "json.php",
    type: "POST",
    data: {userID:72771381},
    dataType: "JSON",
    success: function (msg) {
        console.log(msg);
        document.getElementById("ajax_msg").innerHTML = msg;
        var obj = JSON.stringify(msg); // 문자열로 변경된다.
        $('#json2string').html(obj);
        var objsplit1 = obj.split(']');
        var objsplit2 = objsplit1[0].split('[');
        console.log(objsplit2[1]);
        var rs = JSON.parse(objsplit2[1]);
        console.log('idx = '+rs.idx);

        var arr= new Array();
        $.each(msg, function(key, obj){
            $.each(obj,function(k,value){
                arr.push(value)
            });
        });
        console.log(arr);
    }
});


var myObject = new Object();
myObject.name = "왈패";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
var myString = JSON.stringify(myObject);
$("#stringify").html(myString);

</script>
</body>
</html>
 


마지막 myObject 를 JSON.stringify 를 하면 맨 처음과 똑같은 형태의 중괄호({})로 둘러쌓인 문자열이 만들어진다는 걸 확인할 수 있다.


결론 PHP 에서 넘어온 JSON 형태는 jQuery 가 처리하려는 형태와 약간 다르므로 이걸 고려해서 파싱처리해야 한다는 것이다.

블로그 이미지

Link2Me

,
728x90

PHP에서 json_encode 로 데이터를 만들어서 jQuery 에서 ajax를 이용하여 원하는 데이터를 처리하는 방법이다.


$sql ="select userNM,telNO,mobileNO,codeID FROM member ";
$sql.="where userID='".$_REQUEST['userID']."'";
$result = mysqli_query($db,$sql);
$R = array();
if($row = mysqli_fetch_assoc($result)):
    array_push($R,$row);
endif;
echo json_encode($R);
 



jQuery ajax 로 결과를 받은 데이터는 JSON object 인데 그냥은 원하는 결과를 파싱할 수가 없다.

실력이 부족해서인지 개념부족인지 여기서 막힌다.

( 참조하면 왜 그런지 알 수 있다 : https://link2me.tistory.com/1595 )

그래서 Array로 변환하여 데이터를 처리했다.


 $('#getStaffData').on('click',function(){
    var userID = $('input[name=userID]').val();
    if(userID.length == 0){
        alert('입력값이 없습니다.');
        $('input[name=userID]').focus();
        return false;
    }

    $.ajax({
        url: "StaffFetchData.php",
        type: "POST",
        data: {userID:userID},
        dataType: "JSON",
        success: function (data) {
            //console.log(data);
            var arr= new Array();
            $.each(data, function(key, obj){
                $.each(obj,function(k,value){
                    arr.push(value)
                });
            });
            console.log(arr);
            $('input[name=userNM]').val(arr[0]);
            $('input[name=telNO]').val(arr[1]);
            $('input[name=mobileNO]').val(arr[2]);
            $('#codeID').val(arr[3]);
        }
    });

});


로컬에서 만든 임의의 데이터와 PHP를 통해 가져온 데이터의 차이점이 있다는 걸 알아야 한다.

Android 에서 JSON 데이터를 파싱처리하고자 한다면 파싱 처리하는 코드를 알아야 처리할 수 있다.

블로그 이미지

Link2Me

,
728x90

DB에서 구한 URL 를 가지고 PHP 를 이용하여 JSON 파일로 만드는 코드 예제다.


<?php
if(isset($_POST['id']) && !empty($_POST['id'])){
    $id=$_POST['id'];
    require_once 'path.php';// root 폴더를 기준으로 상대경로 자동 구하기
    require_once $g['path_class'].'connect.php';
    $sql = "SELECT * FROM menu_items where id='{$id}'";
    $result = mysqli_query($db, $sql);
    if($row=mysqli_fetch_array($result)){
        //echo $row['url'];
        $url = $row['url'];
    }

    if($url !== '#'){
        $data = file_get_contents($url);
        $R = json_decode($data,TRUE); // JSON to Array
        echo json_encode($R); // JSON
    }
}
?>
 


블로그 이미지

Link2Me

,
728x90

JSON 데이터 포멧으로 Web URL 데이터를 받아서 PHP 배열로 변환하여 파싱하는 방법이다.


<?php
$url = "http://100.10.10.10/chart/data.json";
$data = file_get_contents_curl($url);

//echo $data.'<br />';

$R = json_decode($data,TRUE);// JSON 데이터를 배열로 변환

foreach($R['content'] as $val) {
    echo $val['sysdate'] . ' | ' . $val['mcount'] . "<br />";
}

function file_get_contents_curl($url) {
    $ch = curl_init();// curl 리소스를 초기화
    curl_setopt($ch, CURLOPT_URL, $url); // url을 설정
    // 헤더는 제외하고 content 만 받음
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 응답 값을 브라우저에 표시하지 말고 값을 리턴
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);// 리소스 해제를 위해 세션 연결 닫음
    return $data;
}

?>
 


블로그 이미지

Link2Me

,
728x90

jQuery 기능을 익히고자 파싱 테스트를 해봤다.

크롬브라우저에서 시도하면 https://brunch.co.kr/@adrenalinee31/1 에서 2. 외부요청을 가능하게 해주는 플러그인 설치를 하면 파싱이 잘 된다.

원하는 조건의 selector 를 찾느라고 좀 삽질을 했다.

$(html).find('.wiki-heading').find("a:contains('3.2.')").parent().next().find(".wiki-link-internal")



<!DOCTYPE html>

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

<script>
var weburl ='https://namu.wiki/w/KBO%20%EB%A6%AC%EA%B7%B8/2018%EB%85%84/%EC%8B%A0%EC%9D%
B8%EB%93%9C%EB%9E%98%ED%94%84%ED%8A%B8'

$.get(weburl, function( html ) {
    var data = new Array();
    // 찾으려는 className 을 반복적으로 찾는다.
    var heading = $(html).find('.wiki-heading').find("a:contains('3.2.')").text();
    //console.log(heading);
    var nextclass = $(html).find('.wiki-heading').find("a:contains('3.2.')").parent().next().find(".wiki-link-internal");
    $(html).find('.wiki-heading').find("a:contains('3.2.')").parent().next().find(".wiki-link-internal").each( function(){
        var text = $(this).parent().text();
        if(text !== 'kt' && text !== '삼성' && text !== '롯데' && text !== '한화' && text !== 'SK' && text !== 'KIA' && text !== 'LG' && text !== 'NC' && text !== '넥센' && text !== '두산') {
            //console.log(text);
            data.push(text);
        }
    });

    for(var i=0;i<data.length;i++){
        console.log(data[i]);
    }
});
</script>

</body>
</html>



파싱 결과


크롬 브라우저 콘솔상에서 연습해보던 Javascript 코드

var data = document.querySelectorAll('.wiki-table-wrap .wiki-table .wiki-link-internal');
for(var i=0;i<data.length;i++){
    var t = data[i];
    t = t.innerText;
    console.log(t);
}


블로그 이미지

Link2Me

,
728x90

PHP 에서 배열의 결과를 json 으로 반환하는 코드다.

네이버지식인에 간혹 화면에 결과가 없다고 질의가 올라오는 코드라서 아주 간단하게 적어본다.

json_encode 는 UTF-8로 된 것만 인식한다고 이해하면 된다.

DB, 서버와의 통신, 파일 인코딩 모드를 모두 UTF-8로 기본 설정해야 한다.


아래 코드를 파일로 첨부한다. 친절하게 테스트해보라고 테이블 구조까지 포함했다.


JSON.zip



<?php
extract($_GET);
$userID ="jsk005@naver.com"; // $_GET 배열로 넘어온 데이터라고 가정한다.

include_once 'dbconnect.php';

$sql = "SELECT * FROM members WHERE userID='".$userID."'";

$result = mysqli_query($dbconn,$sql) or die(mysqli_error($dbconn));
$R = array();
while($row = mysqli_fetch_array($result)){
array_push($R, array("userID"=>$row['userID'], "userNM"=>$row['userNM'], "OSType"=>$row['OStype']));
}

//echo '<pre>';print_r($R);echo '</pre>'; // 데이터가 제대로 들어있는지 확인 용도

echo json_encode(array("result"=>$R)); // 출력은 파일 Encoding 모드가 UTF-8 이어야 한다.
mysqli_close($dbconn);
?>

<?php
$dbconn = isConnectDb(); // DB 연결 함수

function isConnectDb(){
    $dbhost = 'localhost';
    $database = 'test';
    $dbuser = 'root';
    $dbpass = 'autoset';
    $dbport = "3306";
    $conn = mysqli_connect($dbhost,$dbuser,$dbpass,$database,$dbport);
    mysqli_set_charset($conn, "utf8");  // DB설정이 잘못되어 euc-kr 로 되어 있으면 문제가 됨
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        exit;
    } else {
        return $conn;
    }
}
?>



블로그 이미지

Link2Me

,
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

,
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

,
728x90

특정 지역의 날씨정보를 기상청으로부터 가져오는 코드에 대해 알아보고 적어둔다.


기상청 rss 를 통해 동네예보 rss 구하기

http://www.kma.go.kr/weather/lifenindustry/sevice_rss.jsp?sido=4100000000&gugun=4146500000&dong=4146554000&x=27&y=14


1번을 누르면 해당지역 rss 에 대한 날씨예보 정보(현재 온도, 시간별 날씨, 강수량, 기온, 습도 등)가 검색된다.

http://www.kma.go.kr/wid/queryDFSRSS.jsp?zone=4146554000


크롬브라우저와 Firefox가 다르게 검색된 결과를 보여준다.

Firefox 에서는


라고 검색된다.


http://www.kma.go.kr/wid/queryDFS.jsp?gridx=62&gridy=122


X좌표값과 Y좌표값을 넣고 위 URL를 웹브라우저에 입력하면 해당지역 XML 코드가 출력된다.


temp : 온도, hour : 시간, wfKor : 날씨, pop : 강수량, reh : 습도



PHP에서 Web상의 XML 문서를 파싱하기 위해서는 cURL 라이브러리를 이용하면 된다.

String 으로 추출된 결과물을 simplexml_load_string 으로 구조체로 변환한다.

XML 데이터를 JSON 으로 변환한 다음 배열(array)를 읽어서 원하는 자료를 추출하는 것은 foreach 문을 사용하면 되는거 같다.

배열을 출력하는 print_r 함수를 이용하여 내용을 봐가면서 원하는 자료만 추출하면 된다.


<?php

function file_get_contents_curl($url) {
    $ch = curl_init();// curl 리소스를 초기화
    curl_setopt($ch, CURLOPT_URL, $url); // url을 설정
    // 헤더는 제외하고 content 만 받음
    curl_setopt($ch, CURLOPT_HEADER, 0);
    // 응답 값을 브라우저에 표시하지 말고 값을 리턴
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);// 리소스 해제를 위해 세션 연결 닫음
    return $data;
}


$url = "http://www.kma.go.kr/wid/queryDFS.jsp?gridx=62&gridy=122";

$xml_string = file_get_contents_curl($url);

$xml = simplexml_load_string($xml_string);

$json = json_encode($xml); // XML to JSON

$R = json_decode($json,TRUE);//배열로 변환


print_r($R);

echo '<br />';

echo '<br />';

echo $R['header']['tm'].'<br />';//날씨 예보시간

$wData = $R['body']['data'][0];

print_r($wData);

echo '<br />';

echo '<br />';

//echo $wData['hour'].'시 온도:'.$wData['temp'].' 날씨:'.$wData['wfKor'];


foreach($R['body']['data'] as $wData){

    echo $wData['hour'].'시 온도:'.$wData['temp'].' 날씨:'.$wData['wfKor'];

    echo '<br />';

}

?>


위 코드에서 JSON 으로 변경하지 않고 처리한다면

$data = file_get_contents_curl($url);
$xml = simplexml_load_string($data);

echo '<pre>';
print_r($xml);
echo '</pre>';

foreach ($xml->body->data as $row) {
    $hour = $row -> hour;
    $temp = $row -> temp;
    $wfkor = $row -> wfKor;
    $pop = $row -> pop;
    $reh = $row -> reh;
    $wdkor = $row -> wdKor;
}

와 같이 처리하면 원하는 걸 뽑아낼 수 있다.


배열에 나오는 날씨는 내일과 모레 날씨 정보를 보여주는 거 같다.

다음날 오전에 다시 확인해보니 내일, 모레 뿐만 아니라 현재 기준으로 앞으로의 오늘 날씨 정보도 보여주더라.

그런데 날짜 정보가 XML 파일에 기록되지 않아서 해당 정보를 정확하게 파악하기가 쉽지 않다.


cURL 함수 사용이 가능한지 여부를 확인하는 방법

 <?php
if (ini_get('allow_url_fopen') == '1') {
   // file_get_contents() 사용
   echo 'php.ini 환경에서 허용';
} else {
   // curl 함수 이용 가능 여부
   if (function_exists('curl_init')) {
       echo 'curl 함수 사용 가능';
   } else {
       echo 'curl 함수 이용 불가';
   }
}
?>


php.ini에는 'allow_url_fopen'라는 설정항목이 있다.
이 항목이 off일 경우에는 fopen 등의 파일관련 함수에서 URL로 파일을 읽어오는 것이 불가능하다.
'allow_url_fopen'을 off로 하는 대부분의 이유는 '보안 취약성'의 우려가 있기 때문이다.
For example, somebody might pass /etc/passwd as a url, and be able to view its contents.

블로그 이미지

Link2Me

,
728x90

PHP 에서 JSON 데이터를 파싱하는 방법이다.

JSON 데이터는 Local File 을 읽어오는 것과 Web 사이트에서 해당 URL 을 읽어오는 방법이 있다.

가장 먼저 파싱해야 할 데이터 형태 파악을 하는 코드부터 살펴보고자 구글링을 했더니 관련 코드가 있어서 주석을 좀 더 추가하고 이해를 돕는 걸 첨가하여 적어둔다.


 <?php
// Web JSON 파일 읽어오기
$url = 'http://ip주소/getFileList.php';
$json_string = file_get_contents($url);

// Local JSON 파일 읽어오기
//$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

foreach ($R as $key => $val) {
    if(is_array($val)) { // val 이 배열이면
        echo "$key:<br/>";
        //echo $key.' (key), value : (array)<br />';
    } else { // 배열이 아니면
        echo "$key => $val <br />";
    }
}
?>


위 코드로 형태파악을 한 다음에 필요한 것을 파싱처리하면 된다.


Local JSON 파일을 읽어서 처리하는 걸 예제로 보자.

 [
    {
        "firstName": "길동",
        "lastName": "홍",
        "email": "jdhongv@gmail.com",
        "mobile": "010-1234-1111"
    },
    {
        "firstName": "민아",
        "lastName": "김",
        "email": "minakim@gmail.com",
        "mobile": "010-1234-3333"
    },
    {
        "firstName": "진주",
        "lastName": "마",
        "email": "jjmah@gmail.com",
        "mobile": "010-1234-5555"
    },
    {
        "firstName": "서영",
        "lastName": "이",
        "email": "sylee@gmail.com",
        "mobile": "010-1234-7777"
    }
]


<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('data.json');
$R = json_decode($json_string, true);
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.
// $R : array data


foreach ($R as $row) {
    print $row['lastName'];
    print $row['firstName'];
    print ' , ';
    print $row['email'];
    print ' , ';
    print $row['mobile'];
    print '<br />';
}
?> 


결과

홍길동 , jdhongv@gmail.com , 010-1234-1111
김민아 , minakim@gmail.com , 010-1234-3333
마진주 , jjmah@gmail.com , 010-1234-5555
이서영 , sylee@gmail.com , 010-1234-7777


조금 더 복잡한 JSON 파일을 검색한 걸 테스트한다.

{
    "name": "홍길동",
    "alias": "LInk",
    "members": [
        "소원",
        "예린",
        "은하",
        "유주",
        "신비",
        "엄지"
    ],
    "albums": {
        "EP 1집": "Season of Glass",
        "EP 2집": "Flower Bud",
        "EP 3집": "Snowflake",
        "EP 4집": "THE AWAKENING"
    }
}


파싱하는 코드를 두가지로 테스트해보면 print_r 에서 결과를 다르게 보여준다.

<?php
// JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
// 다차원 배열 반복처리
$R = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json_string, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R);
echo '<br />';

foreach ($R as $key => $val) {
    if(is_array($val)) {
        echo "$key:<br/>";
    } else {
        echo "$key => $val<br/>";
    }
}
?>

<?php
// Local JSON 파일 읽어오기
$json_string = file_get_contents('weather.json');
$R = json_decode($json_string, true); //
// $R : array data
// json_decode : JSON 문자열을 PHP 배열로 바꾼다
// json_decode 함수의 두번째 인자를 true 로 설정하면 무조건 array로 변환된다.

print_r($R); // 배열 요소를 출력해준다.
echo '<br />';
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>PHP JSON parser sample</title>
    </head>

    <body>
        <h3 id="gname">
        <?php
            echo $R['name'];
            if (array_key_exists('alias', $R))
                printf(" (%s)", $R['alias']);
        ?>
        </h3>
        <p>멤버 구성: <span id="members">
            <?php echo implode(', ', $R['members']);?></span>
        </p>
        <h3>앨범 목록</h3>
        <ul id="albums">
        <?php
            foreach ($R['albums'] as $key => $value) {
                printf("<li>%s: %s</li>\n", $key, $value);
            }
            ?>
        </ul>
    </body>
</html>


테스트에 사용한 파일 첨부


JSONwithPHP.zip


블로그 이미지

Link2Me

,
728x90

오늘 Android Studio 기반 어플을 테스트 하는데 PHP Array 를 잘못 구현해서 삽질을 한참 했다.


 // 사무실번호, 휴대폰번호, 이름, 소속 등의 정보를 추출
$sql = "select userNM,mobileNO,telNO,sosok from Person ";
$sql .= "where mobileNO='".$search."'";

$R = array(); // 결과 담을 변수 생성
$result = mysqli_query($dbconn,$sql);
while($row = mysqli_fetch_object($result)) {
    array_push($R, $row);
}
echo json_encode(array("result"=>$R));


모든 정보를 select 문으로 가져와서 array_push 에 담은 경우에는 아무런 문제가 되지 않는다.


그런데 sosok 정보를 서브 쿼리로도 가져오기가 힘든 경우가 생겼다.

그래서 함수를 만들어서 해당 정보를 가져와서 array_push 에 저장할 때 아무 생각없이 코딩을 했더니 원하는 결과가 나오지 않고 엉뚱한 결과가 나온다.


$search = add_hyphen_telNo($search);
$sosok = Phone2Dept($search);

// 사무실번호, 휴대폰번호, 이름, 소속 등의 정보를 추출
$sql = "select userNM,mobileNO,telNO from SYS_MEMBER ";
$sql.= "where mobileNO='".$search."' or telNO='".$search."' ";

$R = array(); // 결과 담을 변수 생성
$result = mysqli_query($dbconn,$sql);
while($row = mysqli_fetch_object($result)) {
    array_push($R, $row);

    array_push($R, array("sosok"=>$sosok));

}

echo json_encode(array("result"=>$R));
 


잘못된 결과가 나온다.


아래와 같이 풀어서 해결했다. 풀어서 array_push 에 담으면 암호화된 코드를 추가하기도 편하다.


$sosok = Phone2Dept($search);

// 사무실번호, 휴대폰번호, 이름, 소속 등의 정보를 추출
$sql = "select userNM,mobileNO,telNO from SYS_MEMBER ";
$sql.= "where mobileNO='".$search."' or telNO='".$search."' ";

$R = array(); // 결과 담을 변수 생성
$result = mysqli_query($dbconn,$sql);
while($row = mysqli_fetch_array($result)) {
    array_push($R, array("userNM"=>$row[0],"mobileNO"=>$row[1],"telNO"=>$row[2],"sosok"=>$sosok));
}
echo json_encode(array("result"=>$R));


select 문 하나로 해결이 안되는 걸 json 방식으로 안드로이드폰과 통신하려면 위와 같은 방법으로 데이터를 추가하면 해결될 수 있다.


참고 : How to Use JSON Data with PHP or JavaScript

https://www.taniarascia.com/how-to-use-json-data-with-php-or-javascript/


Android 코드에서는

    int responseCode = conn.getResponseCode();
    //System.out.println("GET Response Code : " + responseCode);
    if(responseCode == HttpURLConnection.HTTP_OK){ // 연결 코드가 리턴되면
        bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String json;
        while((json = bufferedReader.readLine())!= null){
            sb.append(json + "\n");
        }
    }
    bufferedReader.close();
}
System.out.println("PHP Comm Out : " + sb.toString());


로 로그 결과를 확인해서 보낸 데이터가 원하는 형태로 넘어오는지 확인을 꼭 하는게 좋다.

              

블로그 이미지

Link2Me

,
728x90

Treeview 를 검색해서 테스트 하다보니 JSON 만드는 방법을 알아야 원하는 결과로 만들어 낼 수 있는 거 같다.


<?php
include_once "connect.php";
require_once 'treeClass.php'; // Tree 클래스
$t = new treeClass();
$sql = "SELECT * FROM treeview_items";
$result = mysqli_query($db, $sql);
while($row = mysqli_fetch_assoc($result)){
    $menu[] = $row;
}

?>


여기까지는 일반적인 형태로 배열화를 하는 방법이다.

만들어진 배열을 가지고 foreach 문을 이용하여 다시 재가공을 해야 한다.


$rows   = array();
$i=0;
foreach ($menu as $r) {
    $rows[$i]['first_name'] = $r->first_name;
    $rows[$i]['last_name'] = $r->last_name;
    $rows[$i]['phone'] = $r->phone;
    $rows[$i]['email'] = $r->email;

    $i++;
}

//keys total & rows is required on jEasyUI
$result = array('total'=>$menu['count'],'rows'=>$rows);
echo json_encode($result);



Android JSON 포멧으로 만드는 가장 일반적인 형태


<?php

include_once "connect.php";

$sql = "SELECT * FROM address";
$res = mysqli_query($db,$sql); 
$result = array(); 
while($row = mysqli_fetch_array($res)){ 
    array_push($result,
    array('id'=>$row[0],'name'=>$row[1],'address'=>$row[2]
    )); 


$json = json_encode(array("result"=>$result)); 

?>


여기서

    array_push($result,
    array('id'=>$row[0],'name'=>$row[1],'address'=>$row[2]
    )); 

부분을

$result['result'][] = $row;

로 하는게 더 편할 수 있다.

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

Parse JSON with PHP (JSON 파싱)  (2) 2017.11.27
PHP Array 활용 JSON  (0) 2017.05.11
[PHP Parsing] Snoopy로 로또번호 추출하기  (0) 2016.08.01
XML 데이터 생성 처리  (0) 2016.06.06
PHP 와 XML 연동처리  (0) 2016.06.04
블로그 이미지

Link2Me

,
728x90
PHP 로 파싱하는 것은 아직 안해봤다. PHP 로 파싱하는 걸 알면 여러모로 편리할 거 같기는 하다.

다른 Web 사이트에 있는 정보를 가져와서 재가공 해야 하는 경우에 Snoopy.class.php 를 활용하면 된다.


Snoopy 클래스 다운로드 http://sourceforge.net/projects/snoopy/files/latest/download


네이버지식인 답변에 올라온 것을 적어둔다.

답변자 출처 : http://dolgo.net/php/questions/85

<?php
include_once 'snoopy/Snoopy.class.php';
$snoopy = new Snoopy;
$getUrl = "http://www.645lotto.net/lotto645Confirm.do?method=byWin&drwNo=710";
$snoopy->fetch($getUrl);
$pattern='/img src="\/img\/common\/ball_(.*?).png/';
preg_match_all($pattern,$snoopy->results,$out); 
for($i=0;$i<=6;$i++){
    echo $out[1][$i]."\n";
}
?>


분석

- $snoopy = new Snoopy; // Class화된 PHP는 객체 생성을 해야 함

- 확장자를 do를 사용하는 것은 PHP 인지 JSP 인지 식별할 수 없게 하기 위함이다.

- 로또번호 회차 표시부분을 수정하면 매번 다르게 보일 것이다.

- fetch($getUrl) : 입력받은 주소의 html소스를 텍스트 형식으로 $results에 저장

- fetchlinks($URI) : fetch와 비슷하지만 링크만을 배열의 형태로 $results에 저장

- fetchtext($URI) : fetch와 비슷하지만 스크립트를 제외한 텍스트만 $results에 저장

- fetchform($URI) : fetch와 비슷하지만 폼 부분을 html형식으로 $results에 저장

- submit($URI, $formvars="", $formfiles="") : 폼에 여러 변수를 붙여서 전송 가능

- setcookies() : 종종 쿠키정보를 유지해야하는 경우가 있을 때 사용

- preg_match 정규식을 사용해서 이제 본문 필요 요소만을 추출



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

Parse JSON with PHP (JSON 파싱)  (2) 2017.11.27
PHP Array 활용 JSON  (0) 2017.05.11
[PHP] MySQL Data to JSON using PHP  (0) 2016.12.22
XML 데이터 생성 처리  (0) 2016.06.06
PHP 와 XML 연동처리  (0) 2016.06.04
블로그 이미지

Link2Me

,
728x90

XML 데이터 생성하여 화면에 보여주거나, 파일로 저장하는 방법에 대한 함수를 시간을 많이 할애하고 테스트하고 적어둔다.

작업을 하다보니 XML 데이터의 칼럼수가 달라지는 경우 일일이 적어주는 것도 일이더라.

그래서 함수로 만들어서 사용하니 매우 편하다.

dbClass.php 에 대한 설명은 http://link2me.tistory.com/1110 참조하면 된다.


<?php
    include_once $_SERVER['DOCUMENT_ROOT'].'/db.info.php';
    require_once $_SERVER['DOCUMENT_ROOT'].'/phpclass/dbClass.php';
    require_once $_SERVER['DOCUMENT_ROOT'].'/phpclass/xmlClass.php';

    $conn = new MySQLDbClass(); // DB 함수
    $DB_CONNECT = $conn->isConnectDb($DB);

    // 화면에 출력할 칼럼 발췌
   $sql ="select (select classname from category where uid=d.cate1) as cat1,(select classname from category where uid=d.cate2) as cat2,subject,content from data d where is_direct=2 and is_checking=0";
   $result = mysql_query($sql,$DB_CONNECT);

    $c = new xmlcreateClass();
    $c->XML2View($result); // XML 데이터 화면 출력
    //$c->XML2File($result); // XML 데이터 파일 서버에 저장
    //$c->XMLDownload($result, 'myTest'); // XML 데이터 파일 PC에 저장

?>



<?php
class xmlcreateClass {

    // MySQL DB 자료를 column 개수, 게시물 총개수 만큼 자동으로 XML로 만들기
    function exportAsXML($result){
        $xml ='<?xml version="1.0" encoding="UTF-8" ?>'."\n";
        $xml.='<ListInfo>'."\n";
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $xml.="<items>"."\n";
            foreach($row as $column => $value) {
                $xml.="<".$column."><![CDATA[".$value."]]></".$column.">"."\n";
            }
            $xml.="</items>"."\n";
        }
        $xml.='</ListInfo>';
        return $xml;
    }

    // XML 데이터를 모니터 화면으로 출력
    // $c->XML2View($result); // XML 데이터 화면 출력
    function XML2View($result) {
        header('Content-type: text/xml');
        echo $this->exportAsXML($result);
    }

    // XML 데이터를 파일로 서버 저장
    function XML2File($result) {
        $destination_path='files/';
        $xmlfile ='XMLSaveFile.xml';
        $filename = $destination_path . $xmlfile;

        @chmod($filename,0707);  // 파일의 소유권이 있는 경우에만 권한 변경

        $file = fopen($filename,"w");
        fwrite($file, $this->exportAsXML($result));
        fclose($file);

        echo '<script>alert("파일저장 완료");</script>';
    }

    // XML 생성 데이터를 PC에 파일로 저장
    function XMLDownload($result, $filename) {
        header("Content-type: application/vnd.ms-excel; charset=UTF-8");
        header("Content-Disposition: attachment; filename = ".$filename."_".date("Ymd").".xml");
        header("Content-Description: PHP5 Generated Data");
        header("Cache-Control: no-cache"); header("Pragma: no-cache");
        echo $this->exportAsXML($result);
        exit;
    }

}  // end of Class
?>

블로그 이미지

Link2Me

,
728x90

PHP 에서 XML 문서로 데이터 출력을 하는 방법에 대해 알아보자.


XML 문서 만들기의 규칙

- 모든 XML 문서들은 정확한 형식을 갖추어야 한다.

- 모든 태그들은 쌍(시작태그, 종료태그)을 이루어야 한다.


PHP XML Parser 는 두가지 종류가 있다.

SimpleXML Parser 와 XML expat Parser이다.

XML expat Parser 는 event 기반 parser 이다. (http://www.w3schools.com/php/php_xml_parser_expat.asp)

XML expat Parser 는 XML 파일 데이터가 많은 경우에 효과적이다.

XML Expat Parser functions 의 구성요소는 3개의 이벤트로 구성되어 있다고 볼 수 있다.

- Start element: from
- Start CDATA section, value: Jani
- Close element: from


<?php

// 1. DB 접속 경로 지정하여 DB를 읽어들인다.
// 2. 읽어들일 XML 파일의 경로를 지정한다. $readFile
// 3. 읽어들일 파일이 XML 파일인지 여부를 검사한다.
// 4. 초기 변수를 선언한다.
// 5. XML parser 를 생성하고 읽어들인 XML 파일을 파싱처리하여 DB에 저장한다.
$parser=xml_parser_create(); // XML parser 생성

// element handler 등록, start/stop 은 함수명
xml_set_element_handler($parser,"start","stop");

// data handler 등록, char 는 함수명
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen($readFile,"r");

//Read data
while (!feof($fp)) { // 파일의 마지막까지
    $data = fgets($fp);  // 파일을 한줄씩 읽어들인다.
    xml_parse($parser,$data,feof($fp)) or
    die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)),
    xml_get_current_line_number($parser)));
}

//Free the XML parser
xml_parser_free($parser);

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
    global $parsedata;
    $parsedata = "";
}

//Function to use at the end of an element
function stop($parser,$element_name) {
    switch($element_name) {
        case "user_id":
            $user_id = $parsedata
            break;
        case "user_email":
            $user_email = $parsedata
            break;
        case "content":
            $content = $parsedata
            break;
        case "item":
            // <item> </item> 으로 하나의 자료가 끝나는 시점이므로 parse data 를 DB에 저장 처리
            // DB 저장시 key 값 기준으로 데이터 중복체크하여 insert, update 처리
            break;
    }
}

//Function to use when finding character data
function char($parser,$data) {
    global $parsedata;
    $parsedata = $data;
}

?>


블로그 이미지

Link2Me

,