编码特殊字符,DOMDocument XML和PHP

时间:2019-02-14 12:02:28

标签: php xml

使用以下字符:Sub Macro1() ActiveSheet.Range(Cells(1, 2), Cells(1, 3)).AutoFilter Field:=1, Criteria1:="2018" Set rng5 = Range("A3", Range("A65536").End(xlUp)).SpecialCells(xlCellTypeVisible) For Each cell In rng5 Range("c" & cell.Row).Value = "Y" Next cell End Sub 进行测试。我的代码使用PHP和DOMDocument构建XML文件。

" & ' < > £

上面的<?php $xml = new DOMDocument(); $xml->formatOutput = true; $root = $xml->createElement('Start_Of_XML'); $xml->appendChild($root); $el = $xml->createElement($node,htmlspecialchars(html_entity_decode($value[$i],ENT_QUOTES,'UTF-8'),ENT_QUOTES,'UTF-8')); $parent->appendChild($el); ?> 方法将这些字符转换为:

htmlspecialchars()

resp。也就是说,双引号,撇号和井号无法得到编码。

如果我将代码调整为使用htmlentities()代替:

" &amp; ' &lt; &gt; £

字符被解析为:

<? $el = $xml->createElement($node,htmlentities(html_entity_decode($value[$i],ENT_QUOTES,'UTF-8'),ENT_QUOTES,'UTF-8')); ?>

因此英镑符号将与其余符号一起转换,但是再次保存XML时,引号和撇号仍无法得到编码。

在搜索了几篇文章后,我不知所措以寻求解决方案?

编辑:

使用Gordon's作为答案,我得到了我所期望的结果,使用的是类似https://3v4l.org/ZksrE的东西

ThW 付出了很大的努力。似乎很全面。我将接受此作为解决方案。谢谢。

1 个答案:

答案 0 :(得分:1)

DOMDocument::createElement()的第二个参数已损坏-仅部分转义,并且不属于W3C DOM标准。在DOM中,文本内容是一个节点。您可以创建它并将其附加到元素节点。这也适用于其他节点类型,例如CDATA部分或注释。 DOMNode::appendChild()返回附加的节点,因此您可以嵌套和链接调用。

$document = new DOMDocument();
$document->formatOutput = true;
$root = $document->appendChild($document->createElement('foo'));
$root
   ->appendChild($document->createElement('one'))
   ->appendChild($document->createTextNode('"foo" & <bar>'));
$root
   ->appendChild($document->createElement('two'))
   ->appendChild($document->createCDATASection('"foo" & <bar>'));
$root
   ->appendChild($document->createElement('three'))
   ->appendChild($document->createComment('"foo" & <bar>'));

echo $document->saveXML();

输出:

<?xml version="1.0"?> 
<foo>
  <one>"foo" &amp; &lt;bar&gt;</one> 
  <two><![CDATA["foo" & <bar>]]></two>
  <three>
     <!--"foo" & <bar>--> 
  </three> 
</foo>

这将根据需要转义特殊字符(例如&<)。引号确实需要转义,因此不会。其他特殊字符取决于编码。

$document = new DOMDocument("1.0", "UTF-8");
$document
   ->appendChild($document->createElement('foo'))
   ->appendChild($document->createTextNode('äöü'));
echo $document->saveXML();

$document = new DOMDocument("1.0", "ASCII");
$document
   ->appendChild($document->createElement('foo'))
   ->appendChild($document->createTextNode('äöü'));
echo $document->saveXML();

输出:

<?xml version="1.0" encoding="UTF-8"?> 
<foo>äöü</foo> 
<?xml version="1.0" encoding="ASCII"?> 
<foo>&#228;&#246;&#252;</foo>