2011-12-23 61 views
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 这是怎么回事?

+0

关于您的UTF-8的问题,只是把它添加到对象,比如'$ DOC =新的DOM文档( “1.0”, “UTF-8”)第二参数;' – Thielicious 2016-08-23 17:59:56

回答

73

你可以试着这样做:

... 
// 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改变缩进字符(S)。你可以后处理,XML与基于替换(例如,用preg_replace)的线由行正则表达式:

$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]); 
+0

相关:[*调试DOMDocument对象在PHP *](http://stackoverflow.com/q/684227/367456)为更受控制的形式的XML打印。 – hakre 2012-03-02 11:52:25

+0

相关:[*使用preg_replace转换缩进(无回调)*](http://stackoverflow.com/q/8616594/367456) – hakre 2013-01-28 10:39:58

+0

我发现*“您可以在创建后立即设置这些参数DOMDocument以及“*不是一个好主意,如果您在处理/比较另一个文档时使用'saveXML',因为它会导致意外的结果。在需要输出之前,最好格式化输出。 – 2016-06-15 22:06:09

3

两个不同的问题:

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

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


参见xmlEncodingencoding

+1

'preserveWhiteSpace = TRUE'可以在你用'DOMDocument'漂亮地打印时得到你的方式 - 只是FYI,而不是有问题的例子,但是如果你从实际上有空白文本节点的现有文件加载。 – hakre 2011-12-24 02:23:56

+0

@hakre为什么'preserveWhiteSpace = TRUE'对XML工作正常,但不适用于HTML? – Yang 2014-11-07 21:15:10

+0

要让浏览器对其进行格式化,必须设置适当的MIME类型。例如:whit: header('Content-type:text/xml'); – Den 2015-08-25 14:07:52

20

随着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

+0

您说SimpleXML,但您使用的是DOMDocument ... – quickshiftin 2015-02-09 05:08:36

+0

@quickshiftin - 输入数据是'SimpleXMLElement'的一个实例。我将编辑答案以使其更加明显。无论如何,我同意你给DOMDocument提供的东西实际上是不相关的。 – 2015-06-02 11:01:57

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();语句将不漂亮打印从$消息导入的内容,但原本在$ DOM内容将被美化打印。

为了实现漂亮的印刷整个$ DOM文档,该行:

$message->preserveWhiteSpace = false; 

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

9
<?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); 
+1

你是否也可以添加解释? – Robert 2016-01-11 10:59:34

+0

在载入xml字符串之前设置formatOutput = true&preserveWhiteSpace = false,否则它没有任何作用---如果你能理解我的英文,哦,你是天才! – sigkill 2016-12-14 08:33:05

1
// ##### 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 
+0

upvoted,因为这个答案包含一个完整的例子! – baris1892 2018-03-04 08:19:28

0

尝试了所有的答案,但没有奏效。也许这是因为我在保存XML之前追加和删除了孩子。 经过大量的谷歌搜索发现this comment在PHP文档。我只需重新加载生成的XML就可以工作。

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