메뉴 건너뛰기

XEDITION

study

PHP SimpleXML Parser

proin 2018.12.31 00:56 조회 수 : 0

 http://jun.hansung.ac.kr/SWP/PHP/PHP%20XML%20SimpleXML.html


SimpleXML 은 XML 데이타를 쉽게 조작하고, 얻게 해주는 PHP 익스텐션(extensions) 이다.


SimpleXML Parser

SimpleXML 은 트리-기반 파서이다.

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

SimpleXML 은  XML 문서를 배열과 객체의 컬렉션 과 같이 반복될 수 있는 데이타 구조로 변환한다.

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

그러나 고급 XML을 다룰 때는 Expat parser 또는 XML DOM을 사용하는 것이 더 낫다.


Installation

PHP 5 부터는 SimpleXML 함수가 PHP 코어의 일부입니다.  이 함수들을 사용하는데 어떤 설치도 필요치 않습니다.


PHP SimpleXML - Read From String

PHP 의 simplexml_load_string() 함수는 문자열(string)로부터 XML 데이타를 읽는데 사용된다.

아래의 예는 문자열에서 XML 데이터를 읽을 수 있는 simplexml_load_string () 함수를 사용하는 방법을 보여줍니다 :
 

Example

<?php
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object");
echo "<pre>";
print_r($xml);
echo "</pre>";
?>

Run example »

위의 코드의 출력은 다음과 같을 것입니다.:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )


Error Handling Tip: XML 문서를 로딩할 때 모든  에러들을 취득할 수 있는 libxml 기능을 활용하여 모든 에러들을 검색할 수 있다. 다음의 예는 깨진 문자열을 로드하려 하는 경우이다 :
 

Example

<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?> 
<document> 
<user>John Doe</wronguser> 
<email>john@example.com</wrongemail> 
</document>"; 

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
    echo "Failed loading XML: ";
    foreach(libxml_get_errors() as $error) {
        echo "<br>", $error->message;
    }
} else {
    echo "<pre>";
    print_r($xml);
    echo "</pre>";
}
?>

Run example »

위의 코드의 출력은 다음과 같을 것입니다.:

Failed loading XML: 
Opening and ending tag mismatch: user line 3 and wronguser
Opening and ending tag mismatch: email line 4 and wrongemail

 


PHP SimpleXML - Read From File

PHP 의 simplexml_load_file () 함수는 파일에서 XML 데이타를 읽는 데 사용된다.

다음과 같은 XML 파일 "note.xml" 이 있다고 가정합니다 :

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

이제 우리는 위의 XML 파일로부터 다른 정보들을 출력하고 싶습니다. :

Example

Output keys and elements of the $xml variable (which is a SimpleXMLElement object):

<?php
$xml=simplexml_load_file("note.xml");
print_r($xml);
?>

Run example »

위의 코드의 출력은 다음과 같을 것입니다.:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me this weekend! )

 


PHP SimpleXML - Get Node Values

"note.xml"  파일에서 노드값(node values) 가져오기:

Example

<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

Run example »


위의 코드의 출력은 다음과 같을 것이다 :
 

Tove
Jani
Reminder
Don't forget me this weekend!

 


PHP SimpleXML - Get Node Values - Loop

다음과 같은 "books.xml" 라 부르는 XML 파일을 가지고 있다고 가정하자 : 

<?xml version="1.0" encoding="utf-8"?>
<bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en-us">XQuery Kick Start</title>
    <author>James McGovern</author>
    <year>2003</year>
    <price>49.99</price>
  </book>
  <book category="WEB">
    <title lang="en-us">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

"books.xml" 파일로부터 노드 값(node values)들을 가져오기:

Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) { 
    echo $books->title . ", "; 
    echo $books->author . ", "; 
    echo $books->year . ", ";
    echo $books->price . "<br>"; 

?>

Run example »

위의 코드의 출력은 다음과 같을 것이다 :

Everyday Italian, Giada De Laurentiis, 2005, 30.00
Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95

 


PHP SimpleXML - Get Attribute Values - Loop

"books.xml" 파일의 <title> 요소의 속성(attribute) 값 가져오기:

Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) { 
    echo $books->title['lang'];
    echo "<br>"; 

?>

Run example »

위의 코드의 출력은 다음과 같을 것이다 :

en
en
en-us
en-us

 


More PHP SimpleXML

PHP SimpleXML 함수에 대하여 더 자세한 내용을 원하신다면 ==>  PHP SimpleXML Reference 를 방문하시오.


 

위로