Angel.King.47
Angel.King.47

Reputation: 7994

DOMDocument->createTextNode not to encode XML

I have XML that i need the user to be able to edit (inside a textarea) to his liking and then readd it to a DOMDocument Here is what i have so far.

$dom = new DOMDocument();
$dom->formatOutput = true;      //Formating the output
$ele = $dom->createElement("someele", "Hello");
$dom->appendChild( $ele );

$string = "<yowhatsup><noway>some text</noway></yowhatsup>";

$ele = $dom->createElement("otherxmlstuff", $string);
$dom->appendChild( $ele );

Now the output encodes the $string variable and that is not good for me as i want the user to be able to add xml as well as a string into my DOMDocument.

Could I do some pre-processing to turn text into a element as well, or am I barking up the wrong tree.

Upvotes: 1

Views: 1932

Answers (2)

lonesomeday
lonesomeday

Reputation: 237817

You need to create a DOMDocumentFragment rather than an element. When you set an element's text – as you do with the createElement method – it is HTML encoded. This is correct behaviour. If you want to include arbitrary XML, use createDocumentFragment and appendXML:

<?php

$dom = new DOMDocument();
$dom->formatOutput = true;      //Formating the output
$ele = $dom->createElement("someele", "Hello");
$dom->appendChild( $ele );

$string = "<yowhatsup><noway>some text</noway></yowhatsup>";

$frag = $dom->createDocumentFragment();
$frag->appendXML($string);
$dom->appendChild( $frag );

But be very careful to sanitise the input that comes from your user. If you don't sanitise well, you will end up with an XSS vulnerability, allowing arbitrary content to be inserted.

Upvotes: 4

VolkerK
VolkerK

Reputation: 96159

You can use DOMDocumentFragment and its appendXML() method, e.g.

<?php
$doc = new DOMDocument();
$doc->formatOutput = true;
$ele = $doc->createElement("someele", "Hello");
    $xmlstuff = $doc->createElement("otherxmlstuff");

        $fragment = $doc->createDocumentFragment();
        $fragment->appendXML("<foo>text</foo><bar>text2</bar>");
        $xmlstuff->appendChild($fragment);

    $ele->appendChild($xmlstuff);
$doc->appendChild( $ele );
echo $doc->saveXML();

prints

<?xml version="1.0"?>
<someele>Hello<otherxmlstuff><foo>text</foo><bar>text2</bar></otherxmlstuff></someele>

Upvotes: 2

Related Questions