A solution to the problem of garbled Chinese in PHP domdocument saving XML

Source: Internet
Author: User
PHP DOMDocument FOR XML operations as long as we are English is no problem, but if the Chinese font will have garbled problems, the following we give you some solutions to this problem.

PHP inside the DOM is UTF8 mechanism, in loadhtml, is to check the character Meta charset to set the encoding, if there is no CharSet, when the iso8859 to deal with, and in this case savexml, the output is UTF8 , so I see garbled.

So that's not quite understandable, for example:

$xml = new DOMDocument (), @ $xml->loadhtml (' <div> I am the test to see </div> ') $dom = new Domxpath ($xml); Echo $dom- >query ('//div ')->item (0)->savexml ();

Open the Web page execution, you will find the output garbled, then how to solve the problem? There are two ways of doing this.

The first: Specify the encoding when loadhtml, the following code refers to the reply from the Php.net Official document, the code is 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: convert the output character by Iconv, with the following code:

Echo iconv ("UTF-8", "Gb18030//translit", $dom->savexml ($n));

The above is a small series to introduce you to the PHP DOMDocument save XML when the Chinese garbled problem solution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Thank you very much for your support for topic.alibabacloud.com!


Related Article

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.