관리 메뉴

웹개발자의 기지개

[php] RSS, xml 파싱하기 1 본문

PHP

[php] RSS, xml 파싱하기 1

http://portfolio.wonpaper.net 2020. 7. 3. 02:18

뉴스 기사 등을 보통은 RSS 형식으로 텍스트 형태로 제공하고 있는데, 이번에는 이러한 xml 형태로 되어 있는 RSS을 파싱해보기로 한다.

 

http://rss.nocutnews.co.kr/news/gyeongnam.xml

view-source:http://rss.nocutnews.co.kr/news/news.xml

크롬에서 F12를 눌러 소스 보기로 실제 원본소스로 세밀히 관찰해 보자.

대략적으로 살펴보면 실제 반복되는 기사부분을 찾아보자.

<item> </item> 이부분이 중점 부분이다.

 

PHP 상에서 xml 형식으로 파싱할때 쓰이는 주요 함수가 simplexml_load_string() 이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?
function readHtmlFile($url) {
        $info = parse_url($url);
       
        $host = $info["host"];
        $port = $info["port"];
        if ($port == 0$port = 80;
     
   
        $path = $info["path"];
        if ($info["query"!= ""$path .= "?" . $info["query"];
        $out = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
        $fp = fsockopen($host$port$errno$errstr30);
        if (!$fp) {
            echo "$errstr ($errno) <br>\n";
        }
   
        else {
   
            fputs($fp$out);
            $start = false;
            $retVal = "";
   
            while(!feof($fp)) {
                $tmp = fgets($fp1024);
                if ($start == true$retVal .= $tmp;
                if ($tmp == "\r\n"$start = true;
            }
   
            fclose($fp);
            // echo $retVal;
            return $retVal;
        }
    }
 
 
$xml_string = "http://rss.nocutnews.co.kr/news/news.xml";
//$xml_string = iconv($enc,'UTF-8',$xml_string);
$xmlstr = readHtmlFile($xml_string);
$xml = simplexml_load_string(trim($xmlstr));
 
//var_dump($xml);
//print_r($xml);
 
echo sizeof($xml->channel->item). "개 <br><br>";
 
for ($i=0;$i<sizeof($xml->channel->item);$i++) {
    echo $i."번 : ";
 
    echo $xml->channel->item[$i]->title . "<br>";
    echo $xml->channel->item[$i]->link . "<br>";
 
    if (isset($xml->channel->item[$i]->children('media', True)->content)) {
        echo $xml->channel->item[$i]->children('media', True)->content->attributes()['url'] . "<br>";
    }
    echo "<br><br>";
}
?>
cs

 

title  과 url 링크, image 부분을 파싱해왔다.

 

그런데, 47번 기사내용을 보면 image 내용의 노드가 아예 없이 xml 코드가 있는 경우가 있었다.

이때에는 

53번 라인과 같이 isset() 함수를 이용하여 True 일때 파싱이 돌아가도록 코딩을 하면 되겠다. 

 

isset() 함수 없이 그냥 돌리면 아래와 같이 해당 노드가 없는데 파싱을 인위적으로 돌리게 되는데, 

아래와 같은 메세지를 접하게 되므로 주의하자.

Warning: main(): Node no longer exists in /home/gncbs/public_html/www/index3.html on line 56

 

끝으로, xml 태그중에 

<media:content width="250" height="141" url="https://file2.nocutnews.co.kr/newsroom/image/2020/07/02/20200702173034732374_16_250_141.jpg" medium="image" />

형태로, media:content 와 그안의 url 속성을 불러올때 유념하여 코딩하도록 하자.

1
2
3
<?
$xml->channel->item[$i]->children('media', True)->content->attributes()['url'];
?>
cs

 

참고사이트1 : How to Parse XML's Media:Content with PHP?

stackoverflow.com/questions/35877048/how-to-parse-xmls-mediacontent-with-php

 

참고사이트2 : http://egloos.zum.com/darky/v/2860556

 

 

 

 

 

 

 

Comments