简体   繁体   English

如何阻止PHP DOM自动转义字符引用?

[英]How to stop PHP DOM from auto-escaping character references?

...or how to do it another way? ...或另一种方式怎么做?

I'm creating a select box using DOMDocument . 我正在使用DOMDocument创建一个选择框。

$field = $this->dom->createElement('select');
$optgroup = $this->dom->createElement('optgroup');

foreach($options as $v) {
   $option = $this->dom->createElement('option');
   $option->setAttribute('value', $v);
   $option->appendChild($this->dom->createTextNode($v));

   $optgroup->appendChild($option);
}

$field->appendChild($optgroup);

Where $options is an array of character references pre-loaded from an icon font: 其中$options是从图标字体预加载的字符引用数组:

array('!', '"', '#', '$', ...);

I need my output to look like this: 我需要我的输出看起来像这样:

<select>
  <optgroup>
    <option value="&#33;">&#33;</option>
    <option value="&#34;">&#34;</option>
    <option value="&#35;">&#35;</option>
    ...
  </optgroup>
</select>

However, using the DOM methods, it auto escapes all the character references: 但是,使用DOM方法,它将自动转义所有字符引用:

<option value="&amp;#33;">&amp;#33;</option>

How can I prevent that from happening? 如何防止这种情况发生?

NOTE: createEntityReference does not work for this as that method only supports entity references and not character references. 注意: createEntityReference对此不起作用,因为该方法仅支持实体引用而不支持字符引用。 Using it causes a fatal error for 'Invalid character error'. 使用它会导致“无效字符错误”的致命错误。

Try a documentFragment instead, and stuff in some pre-made HTML: 改用documentFragment,然后放入一些预制的HTML:

$frag = $dom->createDocumentFragment();
$frag->loadHTML('<option value="&#33;">&#33;</option>');

$dom->appendChild($frag);

DOM is handy for manipulating an existing tree, but it's an incredible PAIN to build a new tree using nothing but DOM operations. DOM对于处理现有树很方便,但是使用DOM操作构建新树是一个令人难以置信的痛苦。 Sometime's it's just easier to build your html/xml with plain string operations and then shove the whole string into DOM in one operation. 有时,使用纯字符串操作来构建html / xml,然后通过一次操作将整个字符串推入DOM会更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM