本文介绍了PHP DOMDocument:将文本安全地添加到元素的最好方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

添加可能包含麻烦字符(例如&,<,>)的字符串时,DOMDocument会发出警告,而不是对字符串进行消毒。

When adding a string that might contain troublesome characters (eg &, <, >), DOMDocument throws a warning, rather than sanitizing the string.

我正在寻找一种使字符串成为xml安全的简洁方法-理想情况下是利用DOMDocument库的东西。

我正在寻找比 preg_replace htmlspecialchars 更好的东西。我看到 DOMDocument :: createTextNode(),但是生成的DOMText对象很繁琐,无法传递给 DOMDocument :: createElement()

I'm looking for something better than preg_replace or htmlspecialchars. I see DOMDocument::createTextNode(), but the resulting DOMText object is cumbersome and can't be handed to DOMDocument::createElement().

为说明问题,此代码:

<?php 

$dom = new DOMDocument;
$dom->formatOutput = true;
$parent = $dom->createElement('rootNode');
$parent->appendChild( $dom->createElement('name', 'this ampersand causes pain & sorrow ') );
$dom->appendChild( $parent );
echo $dom->saveXml();

产生此结果(请参见):

produces this result (see eval.in):

Warning: DOMDocument::createElement(): unterminated entity reference          sorrow in /tmp/execpad-41ee778d3376/source-41ee778d3376 on line 6
<?xml version="1.0"?>
<rootNode>
  <name>this ampersand causes pain </name>
</rootNode>


推荐答案

您将必须创建文本节点并将其附加。我在此答案中描述了问题:

You will have to create the text node and append it. I described the problem in this answer: https://stackoverflow.com/a/22957785/2265374

不过,您可以扩展 DOMDocument 并重载 createElement *()

However you can extend DOMDocument and overload createElement*().

class MyDOMDocument extends DOMDocument {

  public function createElement($name, $content = '') {
    $node = parent::createElement($name);
    if ((string)$content !== '') {
      $node->appendChild($this->createTextNode($content));
    }
    return $node;
  }

  public function createElementNS($namespace, $name, $content = '') {
    $node = parent::createElementNS($namespace, $name);
    if ((string)$content !== '') {
      $node->appendChild($this->createTextNode($content));
    }
    return $node;
  }
}

$dom = new MyDOMDocument();
$root = $dom->appendChild($dom->createElement('foo'));
$root->appendChild($dom->createElement('bar', 'Company & Son'));
$root->appendChild($dom->createElementNS('urn:bar', 'bar', 'Company & Son'));

$dom->formatOutput = TRUE;
echo $dom->saveXml();

输出:

<?xml version="1.0"?>
<foo>
  <bar>Company &amp; Son</bar>
  <bar xmlns="urn:bar">Company &amp; Son</bar>
</foo>

这篇关于PHP DOMDocument:将文本安全地添加到元素的最好方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 17:53