DOMDocument-> createTextNode不对XML进行编码

时间:2011-10-11 12:15:21

标签: php xml domdocument

我有XML,我需要用户能够根据自己的喜好编辑(在textarea内),然后将其读取到DOMDocument这是我到目前为止所拥有的。

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

现在输出对$string变量进行编码,这对我不利,因为我希望用户能够将xml和字符串添加到我的DOMDocument中。

我是否可以进行一些预处理以将文本转换为元素,或者我正在咆哮错误的树。

2 个答案:

答案 0 :(得分:4)

您需要创建DOMDocumentFragment而不是元素。当您设置元素的文本时 - 就像使用createElement方法一样 - 它是HTML编码的。这是正确的行为。如果要包含任意XML,请使用createDocumentFragmentappendXML

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

非常小心清理来自用户的输入。如果您没有很好地清理,最终会出现XSS漏洞,允许插入任意内容。

答案 1 :(得分:2)

您可以使用DOMDocumentFragment及其appendXML()方法,例如

<?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();

打印

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