This article mainly introduces the solution for Chinese garbled characters when DOMDocument in PHP saves xml, which is very good and has reference value, for more information about xml operations, see DOMDocument in php. we only need to use English, but if it is a Chinese font, there will be garbled characters, next we will introduce some solutions to this problem.
PHP's DOM is based on the utf8 mechanism. during loadHTML, the encoding is set by checking the charset of the meta in the character. if there is no charset, it will be processed by iso8859, in this case, utf8 is output when saveXML is executed, so garbled characters are displayed.
This is not quite understandable. for example:
$ Xml = new DOMDocument (); @ $ xml-> loadHTML ('I just want to test it.
'); $ Dom = new DOMXPath ($ xml); echo $ dom-> query (' // P')-> item (0)-> saveXML ();
When you open the web page and execute it, you will find garbled output. how can this problem be solved? There are two methods.
First, specify the encoding when loadHTML is used. the following code references the response from the official php.net document. the code is as follows:
$doc = new DOMDocument();$doc->loadHTML('
' . $html);foreach ($doc->childNodes as $item){if ($item->nodeType == XML_PI_NODE){$doc->removeChild($item); // remove hack}}$doc->encoding = 'UTF-8'; // insert proper
Method 2: Use iconv to re-convert the output characters. the code is as follows:
echo iconv("UTF-8", "GB18030//TRANSLIT", $dom->saveXML($n) );
The above is a solution for garbled Chinese characters when DOMDocument in PHP is saved in xml. I hope it will help you. if you have any questions, please leave a message, the editor will reply to you in a timely manner. I would like to thank you for your support for PHP chinnet!
For more articles about solutions to Chinese garbled characters when DOMDocument is saved in PHP, please follow PHP's Chinese website!