我正在使用 PHP DOMDocument 库来创建一个带有 javascript 值的“脚本”标记元素并将其插入 DOM。
这是我的做法:
$scriptElement = $doc->createElement('script',$scriptTagVal);
echo $scriptElement->nodeValue;
$someNode->parentNode->insertBefore($scriptElement,$postRttScriptNode);
这符合我的预期,它在“someNode”之前插入了一个元素。但是,它做了一些奇怪的事情,它混淆了符号 (&)。单符号 (&) 不存在,双符号 (&&) 被购买为单符号。
疯了吗?好吧,我试过这样做:
$scriptElement = $doc->createElement('script','return "undefined" !== typeof b **&&** null !== b ? b.getAttribute("content") : 0');
如果我回显 $scriptElement->nodeValue,
我明白了
return "undefined" !== typeof b **&** null !== b ? b.getAttribute("content") : 0'
我假设这几乎是闻所未闻的,但我尝试创建不同的元素,其值包含双符号。像这样的东西:
$scriptElement = $doc->createElement('p','Why does DOMDocument obfuscate double
ampersands(&&)');
输出到我的浏览器的结果是一个
标签,其值为:
为什么 DOMDocument 会混淆 double 符号(
也许是特殊字符?无论如何我可以解决这个问题吗?我的意思是,肯定有一种方法可以使用 DOMDocument 在 HTML 中插入 javascript,对吧?
最佳答案
如 http://www.php.net/manual/en/domdocument.createelement.php 中所述
The value will not be escaped. Use DOMDocument::createTextNode() to create a text node with escaping support
有了它你可以试试:
$doc = new DomDocument();
$scriptContent = 'return "undefined" !== typeof b **&&** null !== b ? b.getAttribute("content") : 0';
$scriptElement = $doc->createElement('script');
$scriptElement->appendChild($doc->createTextNode($scriptContent));
$doc->appendChild($scriptElement);
echo $doc->saveXML();
在构建文本节点时,您可能需要使用 $doc->ownerDocument->createTextNode()
,这是未经测试的,因为我没有可运行的代码片段。
关于PHP DOMDocument createElement 混淆符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24376808/