代码之家  ›  专栏  ›  技术社区  ›  Greg

php文档格式

  •  1
  • Greg  · 技术社区  · 15 年前

    我在修改文档结构时尝试格式化xml输出时遇到了奇怪的行为。

    我基于DomDocument创建了简单的Item类:

    class Item extends DOMDocument {
    
    private $root;
    
    function __construct($version = null, $encoding = null) {
        parent::__construct($version, $encoding);
        $this->formatOutput = true;
        $this->root = $this->createElement("root");
        $this->root = $this->appendChild($this->root);
    }
    
    function build($name) {
        $item = $this->createElement("item");
        $name = $this->createTextNode($name);
        $item->appendChild($name);
        $this->getElementsByTagName("root")->item(0)->appendChild($item);
    }
    }
    

    现在,我有一个小用例:

    $it = new Item('1.0', 'iso-8859-1');
    $it->build("first");
    $it->build("seccond");
    $xml = $it->saveXML();
    
    echo $xml;
    
    $it2 = new Item('1.0', 'iso-8859-1');
    $it2->loadXML($xml);
    
    $it2->build("third");
    $it2->build("fourth");
    $it2->build("fifth");
    $it2->formatOutput = true;
    
    $xml2 = $it2->saveXML();
    
    echo $xml2;
    

    <?xml version="1.0" encoding="iso-8859-1"?>
    <root>
      <item>first</item>
      <item>seccond</item>
    </root>
    <?xml version="1.0" encoding="iso-8859-1"?>
    <root>
      <item>first</item>
      <item>seccond</item>
    
    <item>third</item><item>fourth</item><item>fifth</item></root>
    

    我想这是我错过的东西。也许这是我在打开文档后将节点附加到根目录的方式,也许是一些神奇的设置。

    代码起作用,但我想知道是什么原因导致这种奇怪的行为。

    1 回复  |  直到 9 年前
        1
  •  2
  •   VolkerK    15 年前

    您可以通过设置 preserveWhiteSpace

    $this->formatOutput = true;
    $this->preserveWhiteSpace  = false;
    $this->root = $this->createElement("root");
    
    推荐文章