PHP XML Nice 형식을 출력하는 방법
코드는 다음과 같습니다.
$doc = new DomDocument('1.0');
// create root node
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
$signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df');
// process one row at a time
foreach ($signed_values as $key => $val) {
// add node for each row
$occ = $doc->createElement('error');
$occ = $root->appendChild($occ);
// add a child node for each field
foreach ($signed_values as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}
}
// get completed xml document
$xml_string = $doc->saveXML() ;
echo $xml_string;
브라우저에서 인쇄하면 다음과 같은 XML 구조를 얻을 수 없습니다.
<xml> \n tab <child> etc.
나는 그냥 이해한다
<xml><child>ee</child></xml>
그리고 나는 utf-8이 되고 싶다. 어떻게 이 모든 것이 가능한가?
다음과 같이 해 볼 수 있습니다.
...
// get completed xml document
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
$xml_string = $doc->saveXML();
echo $xml_string;
이러한 파라미터는 작성 직후에 설정할 수 있습니다.DOMDocument
또, 다음과 같이 합니다.
$doc = new DomDocument('1.0');
$doc->preserveWhiteSpace = false;
$doc->formatOutput = true;
그게 더 간결할 것 같아요.두 경우 모두 출력은 (데모):
<?xml version="1.0"?>
<root>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
<error>
<a>eee</a>
<b>sd</b>
<c>df</c>
</error>
</root>
다음을 사용하여 들여쓰기 문자를 변경하는 방법을 알 수 없습니다.DOMDocument
. XML을 행별 정규 표현에 기초한 치환(예: 를 사용하여)으로 후처리할 수 있습니다.
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
또는 XML 데이터도 인쇄할 수 있는 깔끔한 확장 기능도 있습니다.들여쓰기 수준을 지정할 수 있지만, 아무리 깔끔해도 탭은 출력되지 않습니다.
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
SimpleXml 오브젝트를 사용하면 간단하게
$domxml = new DOMDocument('1.0');
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
/* @var $xml SimpleXMLElement */
$domxml->loadXML($xml->asXML());
$domxml->save($newfile);
$xml
simplexml 객체입니다.
그러면 simpleXml을 지정한 새 파일로 저장할 수 있습니다.$newfile
<?php
$xml = $argv[1];
$dom = new DOMDocument();
// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block
$dom->loadXML($xml);
$out = $dom->saveXML();
print_R($out);
모든 답을 시도해 봤지만 소용이 없었다.XML을 저장하기 전에 하위 항목을 추가 및 삭제하기 때문일 수 있습니다. 많은 구글링 후 이 코멘트가 php 문서에서 발견되었습니다.XML을 새로고침만 하면 동작합니다.
$outXML = $xml->saveXML();
$xml = new DOMDocument();
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;
$xml->loadXML($outXML);
$outXML = $xml->saveXML();
// ##### IN SUMMARY #####
$xmlFilepath = 'test.xml';
echoFormattedXML($xmlFilepath);
/*
* echo xml in source format
*/
function echoFormattedXML($xmlFilepath) {
header('Content-Type: text/xml'); // to show source, not execute the xml
echo formatXML($xmlFilepath); // format the xml to make it readable
} // echoFormattedXML
/*
* format xml so it can be easily read but will use more disk space
*/
function formatXML($xmlFilepath) {
$loadxml = simplexml_load_file($xmlFilepath);
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($loadxml->asXML());
$formatxml = new SimpleXMLElement($dom->saveXML());
//$formatxml->saveXML("testF.xml"); // save as file
return $formatxml->saveXML();
} // formatXML
다음 두 가지 다른 문제가 있습니다.
formatOutput 및 preserveWhiteSpace 속성을 다음과 같이 설정합니다.
TRUE
포맷된 XML을 생성하려면:$doc->formatOutput = TRUE; $doc->preserveWhiteSpace = TRUE;
많은 웹 브라우저(Internet Explorer 및 Firefox)가 XML을 표시할 때 XML을 포맷합니다.소스 보기 기능 또는 일반 텍스트 편집기를 사용하여 출력을 검사합니다.
xmlEncoding 및 인코딩도 참조하십시오.
이것은 위 테마의 약간의 변형이지만, 다른 사람이 이것을 때리고 이해할 수 없을 경우를 대비해서 여기에 두겠습니다...저처럼요.
saveXML()을 사용하는 경우 대상 DOM 문서의 preserveWhiteSpace는 가져온 노드에 적용되지 않습니다(PHP 5.6).
다음 코드를 고려합니다.
$dom = new DOMDocument(); //create a document
$dom->preserveWhiteSpace = false; //disable whitespace preservation
$dom->formatOutput = true; //pretty print output
$documentElement = $dom->createElement("Entry"); //create a node
$dom->appendChild ($documentElement); //append it
$message = new DOMDocument(); //create another document
$message->loadXML($messageXMLtext); //populate the new document from XML text
$node=$dom->importNode($message->documentElement,true); //import the new document content to a new node in the original document
$documentElement->appendChild($node); //append the new node to the document Element
$dom->saveXML($dom->documentElement); //print the original document
이 문맥에서$dom->saveXML();
스테이트먼트는 $message에서 Import한 콘텐츠를 예쁘게 인쇄하지 않지만 $dom에 있는 콘텐츠는 예쁘게 인쇄됩니다.
$dom 문서 전체의 예쁜 인쇄를 실현하기 위해 다음 행이 있습니다.
$message->preserveWhiteSpace = false;
다음에 포함시켜야 합니다.$message = new DOMDocument();
line - 즉, 노드를 가져온 문서에도 preserveWhiteSpace = false가 있어야 합니다.
@heavenvil의 답변을 바탕으로 이 기능은 브라우저를 사용하여 예쁘게 인쇄됩니다.
function prettyPrintXmlToBrowser(SimpleXMLElement $xml)
{
$domXml = new DOMDocument('1.0');
$domXml->preserveWhiteSpace = false;
$domXml->formatOutput = true;
$domXml->loadXML($xml->asXML());
$xmlString = $domXml->saveXML();
echo nl2br(str_replace(' ', ' ', htmlspecialchars($xmlString)));
}
언급URL : https://stackoverflow.com/questions/8615422/php-xml-how-to-output-nice-format
'itsource' 카테고리의 다른 글
날짜별 Panda DataFrames 필터링 (0) | 2022.09.24 |
---|---|
Spring Boot Rest 서비스에서 파일 다운로드 (0) | 2022.09.24 |
Sublime Text 2에서 Python 코드를 실행하려면 어떻게 해야 하나요? (0) | 2022.09.24 |
is_a와 instance of의 차이점은 무엇입니까? (0) | 2022.09.24 |
파일이 있는지 확인하는 방법? (0) | 2022.09.24 |