Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DOM append child with new line

Tags:

dom

php

My name Rithy.

I don't know how to add new line before appending a new node or element in the xml.

My php:

$dom = new DOMDocument();

$dom->formatOutput = true;

$dom->preserveWhiteSpace = true;

$dom->load($xml_file);

$body = $dom->getElementsByTagName('body')->item(0);

$newelement_seg = $dom->createElement('seg');

$data = $dom->createTextNode(" text 2 ");  

$newelement_seg->appendChild($data);

$body->appendChild($newelement_seg);

$dom->save($xml_file);

XML Before append a new child:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <seg>
        text 1
    </seg>
</body>
</xml>

XML after append a new child:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <seg>
        text 1
    </seg>
    <seg>
        text 2
    </seg>
</body>
</xml>

But I want:

<?xml version="1.0" encoding="UTF-8"?>
    <body>
        <seg>
            text 1
        </seg>
        <seg>
            text 2
        </seg>
    </body>
</xml>
<hr/>

Thanks in advance!

like image 983
Rithy Avatar asked Jul 01 '10 04:07

Rithy


1 Answers

TO SUMMARIZE THE ANSWERS GIVEN:

  1. you have to set formatOutput to true

  2. you have to set ignoreWhiteSpace to false

ie:

$dom = new DomDocument();
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->load($myxmlfile);
like image 141
LoopDuplicate Avatar answered Sep 17 '22 10:09

LoopDuplicate