Solution to Chinese garbled characters when DOMDocument is saved in PHP

Source: Internet
Author: User
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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.