The solution to the garbled problem in Chinese DOMDocument saving XML in PHP _php instance

Source: Internet
Author: User

PHP DOMDocument FOR XML Operations We have no problem with English, but if it is the Chinese font will have garbled problem, below we give you some solutions to this problem.

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

Is that not quite understood, for example:

$xml = new DOMDocument ();
@ $xml->loadhtml (' <div> I was testing to see </div> '); 
$dom = new Domxpath ($xml);
echo $dom->query ('//div ')->item (0)->savexml ();

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

First: Specify the encoding when loadhtml, the following code refers to the reply from the Php.net Official document, the code reads 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 way: by Iconv the character of the output, the code is as follows:

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

The above is a small set to introduce PHP DOMDocument save XML in Chinese when the problem of garbled solution, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.