我有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变量进行了编码,这对我来说并不好,因为我希望用户能够向我的DOMDocument中添加xml和一个字符串。
我是否可以做一些预处理来将文本转换为元素,或者我找错了树。
发布于 2011-10-11 20:23:17
您可以使用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>发布于 2011-10-11 20:24:17
您需要创建一个DOMDocumentFragment而不是一个元素。当您设置一个元素的文本时-就像您对createElement方法所做的那样-它是超文本标记语言编码的。这是正确的行为。如果要包含任意XML,请使用createDocumentFragment和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 );但是要非常小心地清理来自你的用户的输入。如果您不能很好地进行清理,您将得到一个XSS漏洞,从而允许插入任意内容。
https://stackoverflow.com/questions/7725874
复制相似问题