簡體   English   中英

編碼特殊字符、DOMDocument XML 和 PHP

[英]Encoding special chars, DOMDocument XML and PHP

使用以下字符: " & ' < > £進行測試。我的代碼使用 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()方法將這些字符轉換為:

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

分別也就是說,雙引號、撇號和井號無法編碼。

如果我調整代碼以使用 htmlentities() 代替:

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

?>

字符被解析為:

" &amp; ' &lt; &gt; &pound;

因此,英鎊符號與其余符號一起被轉換,但在保存 XML 時,引號和撇號再次無法編碼。

在搜索了幾個帖子后,我不知如何找到解決方案?

編輯:

使用戈登的回答作為基礎,我得到了我正在尋找的結果,使用的是https://3v4l.org/ZksrE

盡管如此, ThW付出了巨大的努力。 看起來很全面。 我將接受這個作為解決方案。 謝謝。

DOMDocument::createElement()的第二個參數被破壞 - 它只是部分轉義,它不是 W3C DOM 標准的一部分。 在 DOM 中,文本內容是一個節點。 您可以創建它並將其附加到元素節點。 這也適用於其他節點類型,如 CDATA 部分或注釋。 DOMNode::appendChild()返回附加節點,因此您可以嵌套和鏈接調用。

此外,您可以設置DOMElement::$textContent屬性。 這將用單個文本節點替換所有后代節點。 不要使用DOMElement::$nodeValue - 它與參數有同樣的問題。

$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('one'))
   ->textContent = '"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>
  <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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM