SimpleXML 기본 SimpleXML 사용법
이 참조의 많은 예에는 XML 문자열이 필요합니다. 모든 예제에서 이 문자열을 반복하는 대신 각 예제에 포함된 파일에 넣습니다. 이 포함된 파일은 다음 예제 섹션에 나와 있습니다. 또는 XML 문서를 만들고 simplexml_load_file()을 사용하여 읽을 수 있습니다.
예제 #1 XML 문자열이 있는 example.php 파일 포함
<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
</movies>
XML;
?>
SimpleXML의 단순성은 기본 XML 문서에서 문자열이나 숫자를 추출할 때 가장 명확하게 나타납니다.
예제 #2
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie[0]->plot;
?>
위의 예는 다음을 출력합니다.
So, this language. It's like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary.
PHP의 명명 규칙(예: 하이픈)에 따라 허용되지 않는 문자를 포함하는 XML 문서 내의 요소에 액세스하려면 요소 이름을 중괄호와 아포스트로피로 캡슐화하여 수행할 수 있습니다.
예제 #3
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
echo $movies->movie->{'great-lines'}->line;
?>
위의 예는 다음을 출력합니다.
PHP solves all my web problems
예제 #4 SimpleXML에서 고유하지 않은 요소에 액세스
요소의 여러 인스턴스가 단일 상위 요소의 자식으로 존재하는 경우 일반 반복 기술이 적용됩니다.
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
/* For each <character> node, we echo a separate <name>. */
foreach ($movies->movie->characters->character as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>
위의 예는 다음을 출력합니다.
Ms. Coder played by Onlivia Actora Mr. Coder played by El ActÓr
메모: 속성(이전 예의 $movies->movie)은 배열이 아닙니다. 반복 가능하고 접근 가능한 객체입니다.
예제 #5 속성 사용
지금까지 요소 이름과 값을 읽는 작업만 다루었습니다. SimpleXML은 요소 속성에도 액세스할 수 있습니다. 배열의 요소와 마찬가지로 요소의 속성에 액세스합니다.
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
/* Access the <rating> nodes of the first movie.
* Output the rating scale, too. */
foreach ($movies->movie[0]->rating as $rating) {
switch((string) $rating['type']) { // Get attributes as element indices
case 'thumbs':
echo $rating, ' thumbs up';
break;
case 'stars':
echo $rating, ' stars';
break;
}
}
?>
위의 예는 다음을 출력합니다.
7 thumbs up5 stars
예제 #6 텍스트와 요소 및 속성 비교
요소 또는 속성을 문자열과 비교하거나 문자열이 필요한 함수에 전달하려면 (string
)을 사용하여 문자열로 변환해야 합니다. 그렇지 않으면 PHP는 요소를 객체로 취급합니다.
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
if ((string) $movies->movie->title == 'PHP: Behind the Parser') {
print 'My favorite movie.';
}
echo htmlentities((string) $movies->movie->title);
?>
위의 예는 다음을 출력합니다.
My favorite movie.PHP: Behind the Parser
예제 #7 두 요소 비교
두 개의 SimpleXMLElement는 동일한 요소를 가리키더라도 다른 것으로 간주됩니다.
<?php
include 'example.php';
$movies1 = new SimpleXMLElement($xmlstr);
$movies2 = new SimpleXMLElement($xmlstr);
var_dump($movies1 == $movies2);
?>
위의 예는 다음을 출력합니다.
bool(false)
예제 #8 XPath 사용
SimpleXML에는 기본 제공 XPath 지원이 포함됩니다. 모든 <character>
요소를 찾으려면:
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
foreach ($movies->xpath('//character') as $character) {
echo $character->name, ' played by ', $character->actor, PHP_EOL;
}
?>
'//
'는 와일드카드 역할을 합니다. 절대 경로를 지정하려면 슬래시 중 하나를 생략하십시오.
위의 예는 다음을 출력합니다.
Ms. Coder played by Onlivia Actora Mr. Coder played by El ActÓr
예제 #9값 설정
SimpleXML의 데이터는 일정하지 않아도 됩니다. 개체는 모든 요소를 조작할 수 있습니다.
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$movies->movie[0]->characters->character[0]->name = 'Miss Coder';
echo $movies->asXML();
?>
위의 예는 다음을 출력합니다.
<?xml version="1.0" standalone="yes"?> <movies> <movie> <title>PHP: Behind the Parser</title> <characters> <character> <name>Miss Coder</name> <actor>Onlivia Actora</actor> </character> <character> <name>Mr. Coder</name> <actor>El ActÓr</actor> </character> </characters> <plot> So, this language. It's like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. </plot> <great-lines> <line>PHP solves all my web problems</line> </great-lines> <rating type="thumbs">7</rating> <rating type="stars">5</rating> </movie> </movies>
예제 #10 요소 및 속성 추가
SimpleXML에는 자식과 속성을 쉽게 추가할 수 있는 기능이 있습니다.
<?php
include 'example.php';
$movies = new SimpleXMLElement($xmlstr);
$character = $movies->movie[0]->characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movies->movie[0]->addChild('rating', 'PG');
$rating->addAttribute('type', 'mpaa');
echo $movies->asXML();
?>
위의 예는 다음을 출력합니다.
<?xml version="1.0" standalone="yes"?> <movies> <movie> <title>PHP: Behind the Parser</title> <characters> <character> <name>Ms. Coder</name> <actor>Onlivia Actora</actor> </character> <character> <name>Mr. Coder</name> <actor>El ActÓr</actor> </character> <character><name>Mr. Parser</name><actor>John Doe</actor></character></characters> <plot> So, this language. It's like, a programming language. Or is it a scripting language? All is revealed in this thrilling horror spoof of a documentary. </plot> <great-lines> <line>PHP solves all my web problems</line> </great-lines> <rating type="thumbs">7</rating> <rating type="stars">5</rating> <rating type="mpaa">PG</rating></movie> </movies>
예제 #11 DOM 상호 운용성
PHP에는 SimpleXML과 DOM 형식 간에 XML 노드를 변환하는 메커니즘이 있습니다. 이 예제는 DOM 요소를 SimpleXML로 변경하는 방법을 보여줍니다.
<?php
$dom = new DOMDocument;
$dom->loadXML('<books><book><title>blah</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}
$books = simplexml_import_dom($dom);
echo $books->book[0]->title;
?>
위의 예는 다음을 출력합니다.
blah