반응형
PHP simpleXML 포맷된 방법으로 파일을 저장하는 방법
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);
}
?>
언급URL : https://stackoverflow.com/questions/798967/php-simplexml-how-to-save-the-file-in-a-formatted-way
반응형
'programing' 카테고리의 다른 글
reactjs를 사용하여 원시 html 렌더링 (0) | 2022.09.18 |
---|---|
phpmailer: "응답처" 주소만 사용하여 회신합니다. (0) | 2022.09.18 |
Larabel 5 이메일 전송 시도 중 (0) | 2022.09.18 |
utf8과 latin1의 차이점 (0) | 2022.09.18 |
jboss 서버를 시작하는 중 오류 발생 (0) | 2022.09.18 |