【问题标题】:DOMDocument disable character escapingDOMDocument 禁用字符转义
【发布时间】:2015-05-20 05:28:09
【问题描述】:

我正在尝试禁用 DOMDocument 字符转义。

所以当有来自 JSON 的节点时: "something": "<>shouldnotescape"

我希望它在 xml 中产生完全相同的输出: <something value="<>shouldnotescape"/> 相反,我得到:<something value="<>shouldnotescape"/>

我已经尝试关闭substituteElements 和resolveExternals,还尝试了$this->document->saveXML($this->document->documentElement);,但没有任何效果。

我没有加载 XML,而是遍历 JSON 树并创建 DOMElement。每个元素上的值在保存之前都是非转义的,所以我相信,这应该可以通过 DOMDocument 以某种方式实现。

【问题讨论】:

    标签: php xml json


    【解决方案1】:

    这将是无效的 XML。所以这是不可能的。

    例子:

    <?php
    $dom = new DOMDocument();
    $dom->loadXml('<something value="<>shouldnotescape"/>');
    

    输出:

    Warning: DOMDocument::loadXML(): Unescaped '<' not allowed in attributes values in Entity, line: 1 in /tmp/... on line 3    
    Warning: DOMDocument::loadXML(): attributes construct error in Entity, line: 1 in /tmp/... on line 3
    

    您需要注意,这只是序列化。如果您获取属性的值,实体将被解码:

    <?php
    $dom = new DOMDocument();
    $dom->loadXml('<something value="&lt;&gt;shouldnotescape"/>');
    var_dump($dom->documentElement->getAttribute('value'));
    

    输出:

    string(17) "<>shouldnotescape"
    

    【讨论】:

    • 感谢您的回答,我现在所做的只是在整个 xml 上调用 htmlspecialchars_decode 将其取回。 (这是如此愚蠢的规范)。在你问为什么之前,这是学校项目,这就是原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2012-09-06
    • 2012-10-10
    • 2011-04-01
    • 2011-10-23
    • 2015-02-02
    相关资源
    最近更新 更多