English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In PHP, the DOMDocument for XML operations has no problems with English, but there will be garbled characters if it is Chinese fonts. Below, we will introduce some solutions to this problem for everyone.
PHP's DOM internally is utf8The mechanism for setting encoding in loadHTML is to check the charset in the meta tag of the character, and if there is no charset, it defaults to iso8859has been processed, and in this case, when saveXML is called, the output is utf8, so you see garbled characters.
Is it still not clear? Let me give you an example:
$xml = new DOMDocument(); @$xml->loadHTML('<div>我就是测试看看</>div>'); $dom = new DOMXPath($xml); echo $dom->query('//>div')->item(0)->saveXML();
Open the web page to execute, and you will find that the output is garbled. How to solve this problem? There are two ways.
The first method: specify the encoding when calling loadHTML, the following code is from the official reply of php.net, as follows:
$doc = new DOMDocument(); $doc->loadHTML('<?xml encoding="UTF-8>' . $html); foreach ($doc->childNodes as $item) { if ($item->nodeType == XML_PI_NODE) { $doc->removeChild($item); // >remove hack } } $doc->encoding = 'UTF-8; // insert proper
The second method: re-convert the output characters through iconv, the code is as follows:
echo iconv("UTF-8"", "GB18030//"TRANSLIT", $dom->saveXML($n);
The solutions to the problem of Chinese characters appearing as garbled when saving XML with DOMDocument in PHP that I have introduced to you are as follows. I hope they will be helpful to you. If you have any questions, please leave a message, and I will reply to you in a timely manner. I would also like to express my sincere gratitude to everyone for your support of the Yanahe Tutorial website!