0

我正在尝试在我的根文件夹中输出一个 xml 文件。该文件已创建,但所有元素及其内容都保存在一条直线中,如下所示:

*<?xml version="1.0" encoding="UTF-8"?> <letterA>   <lemma>    <word>word1</word>      <textfiles>title of file</textfiles> <videofiles>video.mp3</videofiles>  </lemma>

* 但我想要这样的东西:

<?xml version="1.0" encoding="UTF-8"?>
<letterA>
  <lemma>
    <word>song1.mp3</word>
    <textfiles>title of file</textfiles>
    <videofiles>video.mp3</videofiles>
  </lemma>
</letterA>

这是我的代码:

<?php    
/* create a dom document with encoding utf8 */
$domtree = new DOMDocument('1.0', 'UTF-8');
$domtree->preserveWhiteSpace = true; 
$domtree->setIndent = (1);

   /* $domtree->formatOutput = (true); */

/* create the root element of the xml tree */
$letterARoot = $domtree->createElement("letterA");
/* append it to the document created */
$letterARoot = $domtree->appendChild($letterARoot);

$alemma = $domtree->createElement("lemma");
$alemma = $letterARoot->appendChild($alemma);

/* you should enclose the following two lines in a cicle */
$alemma->appendChild($domtree->createElement('word','word1));
$alemma->appendChild($domtree->createElement('textfiles','title of file'));
$alemma->appendChild($domtree->createElement('videofiles','video.mp3'));

/* save the file in my root folder */
$domtree->save("firstFile.xml") or die("Error"); 

/* get the xml printed */
/* echo $domtree->saveXML(); */
?>

如果有人可以提供帮助,我将不胜感激。正如你所看到的,我使用了 'preserveWhiteSpace' 和 'setIndent' 但没有用。我也尝试过再次使用'formatOutput'。我担心的不是我的 xml 在浏览器上的外观,而是它在实际文件中的外观(即上面示例中的 firstFile.xml)。提前谢谢。

4

1 回答 1

2

You should add

$domtree->formatOutput = true;

if you want it pretty printed. See formatOutput for details.

In one of the comments (Jochem Blok), it is suggested to turn preserveWhiteSpace off

$domtree->preserveWhiteSpace = false;
于 2013-03-09T23:15:48.733 回答