开发者

php domdocument weird formatting

开发者 https://www.devze.com 2023-01-13 15:51 出处:网络
I am experiencing weird behaviour when trying to format xml output while modifying domdocument structure.

I am experiencing weird behaviour when trying to format xml output while modifying domdocument structure.

I have created simple Item class based on DomDocument:

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

Now, I have small use case here:

$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;

And now the odd bit. I call the script and it produces two xml files as required, however I noticed that formating is somehow lost after I edit the document. It sort of carries on without any indents etc.

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

I am assuming it's something I'm missing here. Maybe it's the way I'm appending nodes to root after opening document, maybe some magic setting开发者_运维百科.

The code does the job, but I was wondering what would be the cause of this weird behaviour.


You can "tell" libxml that leading/trailing whitespaces are not significant (and thus in this case libxml may insert whitespaces to indent elements) e.g. by setting the preserveWhiteSpace property to false.

$this->formatOutput = true;
$this->preserveWhiteSpace  = false;
$this->root = $this->createElement("root");
0

精彩评论

暂无评论...
验证码 换一张
取 消