PHP의 SimpleXML을 사용하여 기존 XML 파일에 일부 데이터를 추가하려고합니다. 문제는 모든 데이터를 한 줄에 추가한다는 것입니다.
<name>blah</name><class>blah</class><area>blah</area> ...
등등. 모두 한 줄에. 줄 바꿈을 도입하는 방법은 무엇입니까?
이렇게 만들려면 어떻게해야하나요?
<name>blah</name>
<class>blah</class>
<area>blah</area>
asXML()
기능을 사용하고 있습니다.
감사.
답변
DOMDocument 클래스 를 사용 하여 코드 형식을 변경할 수 있습니다.
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();
답변
Gumbo의 솔루션이 트릭을 수행합니다. 위의 simpleXml로 작업 한 다음 끝에 이것을 추가하여 에코 및 / 또는 서식으로 저장할 수 있습니다.
아래 코드는이를 에코하고 파일에 저장합니다 (코드의 주석을 확인하고 원하지 않는 것은 제거하십시오).
//Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
//Echo XML - remove this and following line if echo not desired
echo $dom->saveXML();
//Save XML to file - remove this and following line if save not desired
$dom->save('fileName.xml');
답변
dom_import_simplexml
DomElement로 변환하는 데 사용 합니다. 그런 다음 용량을 사용하여 출력을 포맷합니다.
$dom = dom_import_simplexml($simple_xml)->ownerDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
답변
Gumbo 와 Witman이 대답 했듯이 ; DOMDocument :: load 및 DOMDocument :: save 를 사용하여 기존 파일에서 XML 문서를로드하고 저장합니다 (여기에는 많은 초보자가 있습니다) .
<?php
$xmlFile = 'filename.xml';
if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
else
{
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dl = @$dom->load($xmlFile); // remove error control operator (@) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
echo $dom->save($xmlFile);
}
?>
답변
