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();
검보의 솔루션이 효과가 있습니다.위의 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');
DomainElement로 변환하기 위해 사용합니다.그런 다음 해당 용량을 사용하여 출력을 포맷합니다.
$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); } ?>