본문 바로가기

PHP/PHP 함수

[PHP] simplexml_load_file( ) : RSS(XML) 문서 읽기

RSS (Really Simple Syndication)

뉴스나 블로그 사이트에서 주로 사용하는 콘텐츠 표현 방식. 웹 사이트 관리자는 RSS 형식으로 웹 사이트 내용을 보여 준다. RSS가 등장하기 전에는 원하는 정보를 얻기 위해 해당 사이트를 직접 방문하여야 했으나, 자동으로 업데이트 되기 때문에, 사용자는 각각의 사이트 방문 없이 최신 정보들만 골라 한 자리에서 볼 수 있다. <위키백과 참조> 

RSS 는 XML로  아래와 같이 정해진 형식에 따라 작성된다. <출처: w3schools.com/xml/xml_rss.asp>

<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>W3Schools Home Page</title>
  <link>https://www.w3schools.com</link>
  <description>Free web building tutorials</description>
  <item>
    <title>RSS Tutorial</title>
    <link>https://www.w3schools.com/xml/xml_rss.asp</link>
    <description>New RSS tutorial on W3Schools</description>
  </item>
  <item>
    <title>XML Tutorial</title>
    <link>https://www.w3schools.com/xml</link>
    <description>New XML tutorial on W3Schools</description>
  </item>
</channel>

</rss>

 

XML (Extensible Markup Language)

XML W3C에서 개발된, 다른 특수한 목적을 갖는 마크업 언어를 만드는데 사용하도록 권장하는 다목적 마크업 언어이다. XML은 SGML의 단순화된 부분집합으로, 다른 많은 종류의 데이터를 기술하는 데 사용할 수 있다.

<위키백과> 참조

 

 

Parsing

일련의 문자열을 의미있는 token(어휘 분석의 단위) 으로 분해하고 그것들로 이루어진 Parse tree를 만드는 과정

<위키백과> 참조 

 

 

PHP SimpleXML Parser

SimpleXML 은 tree_based parser

SimpleXML 을 사용하면,  XML 문서 구조 또는 레이아웃을 알고 있는 경우 요소의 속성과 텍스트 콘텐츠를 얻는 쉬운 방법을 제공

SimpleXML 은  XML 문서를 배열과 객체의 집합체와 같이 반복될 수 있는 데이타 구조로 변환

DOM 또는 Expat 파서와 비교해서, SimpleXML 은 요소로부터 텍스트 데이타를 읽는데 단지 몇 줄의 코드만 필요(쉽다)

그러나 고급 XML을 다룰 때는 Expat parser 또는 XML DOM을 사용

<https://www.w3schools.com/php/php_ref_simplexml.asp> 참조 

 

 

simplexml_load_file ( ) :  xml 파일을 읽어 들여 객체와 배열의 집합체(?)로 나타낸다. 

 

1. xml 파일일 경우

simplexml_load_file("text.xml")

 

2. 링크일 경우: php 설정을 바꾸어 주어야 함

ini_set("allow_url_fopen", 1);           
simplexml_load_file("http://xml파일의 url");

 

 

<실행예>

RSS 상태의 문서 :  www.kma.go.kr/wid/queryDFSRSS.jsp?zone=1111060000

<rss version="2.0">
	<channel>
      <title>기상청 동네예보 웹서비스 - 서울특별시 종로구 가회동 도표예보</title>
      <link>http://www.kma.go.kr/weather/main.jsp</link>
      <description>동네예보 웹서비스</description>
      <language>ko</language>
      <generator>동네예보</generator>
      <pubDate>2020년 06월 03일 (수)요일 14:00</pubDate>
        <item>
        <author>기상청</author>
        <category>서울특별시 종로구 가회동</category>
        <title>동네예보(도표) : 서울특별시 종로구 가회동 [X=60,Y=127]</title>
        <link>http://www.kma.go.kr/weather/forecast/timeseries.jsp?searchType=INTEREST&dongCode=1111060000</link>
        <guid>http://www.kma.go.kr/weather/forecast/timeseries.jsp?searchType=INTEREST&dongCode=1111060000</guid>
        <description>
          <header>
          <tm>202006031400</tm>
          <ts>4</ts>
          <x>60</x>
          <y>127</y>
          </header>
          <body>
            <data seq="0">
            <hour>18</hour>
            <day>0</day>
            <temp>25.0</temp>
            <tmx>-999.0</tmx>
            <tmn>-999.0</tmn>
            <sky>1</sky>
            <pty>0</pty>
            <wfKor>맑음</wfKor>
            <wfEn>Clear</wfEn>
            <pop>0</pop>
            <r12>0.0</r12>
            <s12>0.0</s12>
            <ws>2.9000000000000004</ws>
            <wd>5</wd>
            <wdKor>남서</wdKor>
            <wdEn>SW</wdEn>
            <reh>60</reh>
            <r06>0.0</r06>
            <s06>0.0</s06>
            </data>
            .
            .
            .
            

 

simplexml_load_file( ) 로 변화후 문서(객체와 배열의 집합체?)

object(SimpleXMLElement)#1 (2) {
  ["@attributes"]=>
  array(1) {
    ["version"]=>
    string(3) "2.0"
  }
  ["channel"]=>
  object(SimpleXMLElement)#2 (7) {
    ["title"]=>
    string(90) "기상청 동네예보 웹서비스 - 서울특별시 강서구 가양제1동 도표예보"
    ["link"]=>
    string(37) "http://www.kma.go.kr/weather/main.jsp"
    ["description"]=>
    string(25) "동네예보 웹서비스"
    ["language"]=>
    string(2) "ko"
    ["generator"]=>
    string(12) "동네예보"
    ["pubDate"]=>
    string(37) "2020년 06월 03일 (수)요일 14:00"
    ["item"]=>
    object(SimpleXMLElement)#3 (6) {
      ["author"]=>
      string(9) "기상청"
      ["category"]=>
      string(39) "서울특별시 강서구 가양제1동"
      ["title"]=>
      string(75) "동네예보(도표) : 서울특별시 강서구 가양제1동 [X=57,Y=127]"
      ["link"]=>
      string(92) "http://www.kma.go.kr/weather/forecast/timeseries.jsp?searchType=INTEREST&dongCode=1150060300"
      ["guid"]=>
      string(92) "http://www.kma.go.kr/weather/forecast/timeseries.jsp?searchType=INTEREST&dongCode=1150060300"
      ["description"]=>
      object(SimpleXMLElement)#4 (2) {
        ["header"]=>
        object(SimpleXMLElement)#5 (4) {
          ["tm"]=>
          string(12) "202006031400"
          ["ts"]=>
          string(1) "4"
          ["x"]=>
          string(2) "57"
          ["y"]=>
          string(3) "127"
        }
        ["body"]=>
        object(SimpleXMLElement)#6 (1) {
          ["data"]=>
          array(19) {
            [0]=>
            object(SimpleXMLElement)#7 (20) {
              ["@attributes"]=>
              array(1) {
                ["seq"]=>
                string(1) "0"
              }
              ["hour"]=>
              string(2) "18"
              ["day"]=>
              string(1) "0"
              ["temp"]=>
              string(4) "23.0"
              ["tmx"]=>
              string(6) "-999.0"
              ["tmn"]=>
              string(6) "-999.0"
              ["sky"]=>
              string(1) "1"
              ["pty"]=>
              string(1) "0"
              ["wfKor"]=>
              string(6) "맑음"
              ["wfEn"]=>
              string(5) "Clear"
              ["pop"]=>
              string(1) "0"
              ["r12"]=>
              string(3) "0.0"
              ["s12"]=>
              string(3) "0.0"
              ["ws"]=>
              string(18) "2.9000000000000004"
              ["wd"]=>
              string(1) "5"
              ["wdKor"]=>
              string(6) "남서"
              ["wdEn"]=>
              string(2) "SW"
              ["reh"]=>
              string(2) "70"
              ["r06"]=>
              string(3) "0.0"
              ["s06"]=>
              string(3) "0.0"
            }
            .
            .
            .