PHP XML如何输出漂亮的格式

时间:2011-12-23 11:19:00

标签: php xml domdocument

以下是代码:

$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 这一切怎么可能呢?

7 个答案:

答案 0 :(得分:93)

您可以尝试这样做:

...
// 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;

这可能更简洁。两种情况下的输出都是(Demo):

<?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);

或者,有tidy extension with tidy_repair_string也可以打印XML数据。可以用它指定缩进级别,但是整洁不会输出制表符。

tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);

答案 1 :(得分:28)

使用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

指定的新文件

答案 2 :(得分:17)

background-position: 50% 0;

答案 3 :(得分:4)

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

答案 4 :(得分:3)

这里有两个不同的问题:

  • formatOutputpreserveWhiteSpace属性设置为TRUE以生成格式化的XML:

    $doc->formatOutput = TRUE;
    $doc->preserveWhiteSpace = TRUE;
    
  • 许多Web浏览器(即Internet Explorer和Firefox)在显示时都会格式化XML。使用“查看源”功能或常规文本编辑器检查输出。


另请参阅xmlEncodingencoding

答案 5 :(得分:3)

尝试了所有的答案但没有奏效。也许是因为我在保存XML之前附加和删除了孩子。 经过大量的谷歌搜索在php文档中找到了this comment。我只需要重新加载生成的XML就可以了。

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

答案 6 :(得分:1)

这是上述主题的略微变化,但我放在这里以防其他人点击这个并且无法理解它...就像我一样。

使用saveXML()时,目标DOMdocument中的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导入的内容,但最初在$ dom中的内容将会打印出来。

为了实现整个$ dom文档的漂亮打印,行:

$message->preserveWhiteSpace = false; 

必须包含在$message = new DOMDocument();行之后 - 即。从中导入节点的文档还必须具有preserveWhiteSpace = false。

相关问题