
DOMDocument::saveXML을 사용하여 XML파일의 내용을 변경하여 저장하는 방법은 다음과 같습니다.
1. XML파일을 DOMDocument 객체로 로드합니다.
#hostingforum.kr
php
$doc = new DOMDocument();
$doc->loadXML('John30');
2. 변경하고 싶은 노드의 태그 이름과 인덱스를 사용하여 노드를 가져옵니다.
#hostingforum.kr
php
$nodeName = $doc->getElementsByTagName('name')->item(0);
$nodeAge = $doc->getElementsByTagName('age')->item(0);
3. 노드의 값을 변경합니다.
#hostingforum.kr
php
$nodeName->nodeValue = 'Jane';
$nodeAge->nodeValue = '31';
4. 변경된 노드를 DOMDocument 객체에 반영합니다.
#hostingforum.kr
php
$doc->saveXML();
5. 변경된 XML파일을 저장합니다.
#hostingforum.kr
php
$doc->save('changed.xml');
예제 코드는 다음과 같습니다.
#hostingforum.kr
php
$doc = new DOMDocument();
$doc->loadXML('John30');
$nodeName = $doc->getElementsByTagName('name')->item(0);
$nodeAge = $doc->getElementsByTagName('age')->item(0);
$nodeName->nodeValue = 'Jane';
$nodeAge->nodeValue = '31';
$doc->save('changed.xml');
echo file_get_contents('changed.xml');
이 예제 코드는 XML파일의 내용을 변경하여 저장하는 방법을 보여줍니다.
2025-07-15 21:52