問題描述
當我嘗試使用 DOMDocument 將 UTF-8 字符串寫入 XML 文件時,它實際上寫入的是字符串的十六進制表示法,而不是字符串本身.
When I try to write UTF-8 Strings into an XML file using DOMDocument it actually writes the hexadecimal notation of the string instead of the string itself.
例如:
ירושלים
代替:
???????
有什么想法可以解決這個問題嗎?
Any ideas how to resolve the issue?
推薦答案
好的,給你:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->appendChild($dom->createElement('root'));
$dom->documentElement->appendChild(new DOMText('???????'));
echo $dom->saveXml();
會正常工作,因為在這種情況下,您構建的文檔將保留指定為第二個參數的編碼:
will work fine, because in this case, the document you constructed will retain the encoding specified as the second argument:
<?xml version="1.0" encoding="utf-8"?>
<root>???????</root>
但是,一旦將 XML 加載到未指定編碼的 Document 中,您將丟失在構造函數中聲明的任何內容,這意味著:
However, once you load XML into a Document that does not specify an encoding, you will lose anything you declared in the constructor, which means:
$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadXml('<root/>'); // missing prolog
$dom->documentElement->appendChild(new DOMText('???????'));
echo $dom->saveXml();
不會有 utf-8 編碼:
will not have an encoding of utf-8:
<?xml version="1.0"?>
<root>ירושלים</root>
因此,如果您加載 XML 內容,請確保它是
So if you loadXML something, make sure it is
$dom = new DOMDocument();
$dom->loadXml('<?xml version="1.0" encoding="utf-8"?><root/>');
$dom->documentElement->appendChild(new DOMText('???????'));
echo $dom->saveXml();
它會按預期工作.
作為替代,您也可以指定編碼 加載文檔后.
As an alternative, you can also specify the encoding after loading the document.
這篇關于PHP:每當我嘗試編寫 UTF-8 時,它都會使用 DOMDocument 寫入它的十六進制表示法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!