UFO ET IT

좋은 형식을 출력하는 방법 PHP XML

ufoet 2020. 11. 29. 12:41
반응형

좋은 형식을 출력하는 방법 PHP XML


코드는 다음과 같습니다.

$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. 줄 단위 정규 표현식 기반 대체 (예 :로 preg_replace)를 사용 하여 XML을 후 처리 할 수 ​​있습니다 .

$xml_string = preg_replace('/(?:^|\G)  /um', "\t", $xml_string);

또는 XML 데이터를 인쇄 할 수 있는 깔끔한 확장 기능tidy_repair_string 이 있습니다. 들여 쓰기 수준을 지정할 수 있지만 깔끔하게 탭을 출력하지 않습니다.

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을 생성 하려면 formatOutputpreserveWhiteSpace 속성을 TRUE설정하십시오 .

    $doc->formatOutput = TRUE;
    $doc->preserveWhiteSpace = TRUE;
    
  • 많은 웹 브라우저 (즉, Internet Explorer 및 Firefox)는 XML을 표시 할 때 형식을 지정합니다. 소스보기 기능 또는 일반 텍스트 편집기를 사용하여 출력을 검사하십시오.


xmlEncodingencoding을 참조하십시오 .


// ##### 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

모든 답변을 시도했지만 아무것도 작동하지 않았습니다. XML을 저장하기 전에 자식을 추가하고 제거했기 때문일 수 있습니다. 많은 인터넷 검색 후 PHP 문서 에서이 주석발견 했습니다 . 결과 XML을 다시로드하기 만하면 작동합니다.

$outXML = $xml->saveXML(); 
$xml = new DOMDocument(); 
$xml->preserveWhiteSpace = false; 
$xml->formatOutput = true; 
$xml->loadXML($outXML); 
$outXML = $xml->saveXML(); 

This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.

When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).

Consider the following code:

$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

In this context, the $dom->saveXML(); statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.

In order to achieve pretty printing for the entire $dom document, the line:

$message->preserveWhiteSpace = false; 

must be included after the $message = new DOMDocument(); line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.

참고URL : https://stackoverflow.com/questions/8615422/php-xml-how-to-output-nice-format

반응형