Chinese garbled characters appear when PHPDOMDocument saves xml

Source: Internet
Author: User
In php, DOMDocument has no problem with xml operations as long as it is in English, but if it is a Chinese font, there will be garbled characters. below we will introduce some solutions to this problem. the php dom is based on the utf8 mechanism... in php, DOMDocument has no problem with xml operations as long as it is in English, but if it is a Chinese font, there will be garbled characters. below 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'm testing. look.-http://www.phprm.com.

'); $ 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 in the official php.net document. the code is as follows:

$doc = new DOMDocument(); $doc->loadHTML('
 ' . $html);  // dirty fix 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) );


Permanent address:

Reprint at will ~ Please bring the tutorial URL ^

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.