【问题标题】:PHP simpleXML how to save the file in a formatted way?PHP simpleXML如何以格式化的方式保存文件?
【发布时间】:2010-10-22 09:19:00
【问题描述】:

我正在尝试使用 PHP 的 SimpleXML 将一些数据添加到现有的 XML 文件中。问题是它在一行中添加了所有数据:

<name>blah</name><class>blah</class><area>blah</area> ...

等等。全部在一条线上。如何引入换行符?

我是怎么做到的?

<name>blah</name>
<class>blah</class>
<area>blah</area>

我正在使用asXML() 函数。

谢谢。

【问题讨论】:

标签: php formatting simplexml


【解决方案1】:

您可以使用DOMDocument class 重新格式化您的代码:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
echo $dom->saveXML();

【讨论】:

  • 谢谢。简单高效。
  • 那么 SimpleXML 是不可能的?
  • @xcy7e 不,我不这么认为。
  • 当我尝试格式化要附加到文件的内容时,只有在加载现有内容之前指定了 preserveWhiteSpace 和 formatOutput 时它才有效。
【解决方案2】:

Gumbo 的解决方案可以解决问题。您可以使用上面的 simpleXml 进行工作,然后将其添加到最后以回显和/或使用格式保存。

下面的代码会回显它并将其保存到文件中(请参阅代码中的 cmets 并删除您不想要的任何内容):

//Format XML to save indented tree rather than one line
$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($simpleXml->asXML());
//Echo XML - remove this and following line if echo not desired
echo $dom->saveXML();
//Save XML to file - remove this and following line if save not desired
$dom->save('fileName.xml');

【讨论】:

    【解决方案3】:

    使用dom_import_simplexml 转换为DomElement。然后使用它的容量来格式化输出。

    $dom = dom_import_simplexml($simple_xml)->ownerDocument;
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    echo $dom->saveXML();
    

    【讨论】:

    • 不起作用。该函数返回一个 DOMElement,而不是 DOMDocument
    • 似乎documentElement 应该是ownerDocument。不确定 api 是否发生了变化,或者这只是一个错字。我现在已经更正了。
    • 请注意,这仍然不起作用,因为应该在导入文档之前设置preserveWhiteSpace和formatOutput :)
    • 很有趣——你是对的。看起来 Gumbo 的答案会起作用。
    【解决方案4】:

    作为GumboWitman 回答;使用 DOMDocument::loadDOMDocument::save 从现有文件(我们这里有很多新手)加载和保存 XML 文档。

    <?php
    $xmlFile = 'filename.xml';
    if( !file_exists($xmlFile) ) die('Missing file: ' . $xmlFile);
    else
    {
      $dom = new DOMDocument('1.0');
      $dom->preserveWhiteSpace = false;
      $dom->formatOutput = true;
      $dl = @$dom->load($xmlFile); // remove error control operator (@) to print any error message generated while loading.
      if ( !$dl ) die('Error while parsing the document: ' . $xmlFile);
      echo $dom->save($xmlFile);
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-19
      • 2022-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      相关资源
      最近更新 更多