PHP DOM adds a newline child

My name is Rifi.

I do not know how to add a new line before adding a new node or element in 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 adding a new child:

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

XML after adding 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!

+3
source share
3 answers

What are you trying to accomplish?

By setting preserveWhiteSpaceto true(optionally, the default), you tell libxml not to ignore text nodes that consist only of white space. However, at the same time, you are trying to format the XML file, which is really needed for nodes with spaces.

, , , <seg> ; libxml ; text 1, </seg> , node .

:

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

libxml, , </seg>, node.

$dom->preserveWhiteSpace = false;:

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

, libxml :

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

<seg>.

, tidy, , , .

+2

, :

  • formatOutput true

  • ignoreWhiteSpace false

$dom = new DomDocument();
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;
$dom->load($myxmlfile);
+6

. . , :

       //create new document object
        $dom_object = new DOMDocument(); 

        //load xml file
        $xml_file_path = get_template_directory()."/flash/playlist.xml";
        $dom_object->formatOutput = true;    
        $dom_object->preserveWhiteSpace = false;
        $dom_object->load($xml_file_path);    
+3

Source: https://habr.com/ru/post/1752573/


All Articles