gpt4 book ai didi

PHP DOMDocument createElement 混淆符号

转载 作者:可可西里 更新时间:2023-11-01 13:54:11 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com