DOM 읽기

우선 DOM이 읽어드릴 HTML 문서나 XML 문서의 예를 들어보자
XML 문서(music.xml)
// DOM 객체의 한국어 인식

//music.xml

<? xml version = "1.0" encoding = "euc-kr"?>
// DOM 객체의 한국어 인식
<music>
<artist id="1">
<name>조용필</name>
<albums>
<title>The Dreams</title>
</albums>
</artist>

<artist id="2">
<name>서태지</name>
<albums>
<title>Feel The Soul</title>
<title>Live Wire</title>
</albums>
</artist>
</music>


#######################

우선 위의 XML 문서를 DOM 객체로 로드하려면, 다음과 같이 DomDocument 객체를 생성한 다음 XML 문서를 로드해야 한다.

$dom = new DomDocument();
$dom->load("music.xml");
//$dom->load("file://music.xml");
//$dom->load(http://www.goodboys.co.kr/music.xml);

XML 문서에서 공백은 의미가 없으므로 XML 문서의 필요없는 공백들을 제거하고자 한다면 다음과 같이 preserveWhiteSpace를 false로 지정해준다.

$dom->preserveWhiteSpace = false;
DOM 객체의 XML 문서를 문자열로 반환하고자 한다면 saveXML() 메소드를 사용한다. 따라서 XML 문서를 화면에 출력하고자 하는 경우에는 다음과 같이 써주면 된다.

print $dom->saveXML();
DOM 객체의 XML 문서를 파일로 저장하고 싶다면
$dom->save("newfile.xml");

이제 생성된 객체 $dom으로 부터 원하는 데이터를 가져올 수 있다. DOM 객체로 부터 원하는 데이터(요소,요소그룹)를 가져오는 가장 쉬운 방법은 getElementByTagName() 메소드를 사용하는 것이다. 이 getElementByTagName() 메소드는 지정한 요소 객체를 배열로 가져온다.

load("music.xml");
$dom->preserveWhiteSpace = false;

// name 요소를 출력

$names = $dom->getElementByTagName('name');

// 배열로 가져다 준다고 했다.

foreach ($names as $name){
print $name->firstChild->nodeValue.'<br>';
//firstChild는 요소의 값이 아니라 요소의 첫 번째 자식을 의미함,
//따라서 firstChild의 nodeValue를 가져와야 한다.
}
?>



실행결과

조용필
서태지
// albums 요소 출력
getElementsByTagName('album');

foreach($albums as $album) {
foreach($album->childNodes as $title) {
print $title->firstChild->nodeValue;
}
}
?>

실행결과

The Dreams
Feel The soul
Live Wire

foreach문을 여러 번 사용하는 방법은 자식 노드가 하나이든 둘이든 상관없이 모든 요소를 가져와 출력할 수 있는 예이다.