PHP generates XML file Chinese character encoding problem

Source: Internet
Author: User
Tags foreach addchild


First look at an array to convert XML

The code is as follows Copy Code

function Array2xml ($array, $xml = False) {
if ($xml = = False) {
$xml = new SimpleXMLElement (' <root/> ');
}
foreach ($array as $key => $value) {
if (Is_array ($value)) {
Array2xml ($value, $xml->addchild ($key));
}else{
$xml->addchild ($key, $value);
}
}
return $xml->asxml ();
}

Header (' Content-type:text/xml ');
Print Array2xml ($array);

So if there is no Chinese characters, no problem.

If there is a problem with Chinese, when the content appears to be empty when the Chinese character, the solution is the transcoding process

The code is as follows Copy Code
/*
Convert PHP array into XML
*/

function Array2xml ($array, $xml = False) {
if ($xml = = False) {
$xml = new SimpleXMLElement (' <root/> ');
}
foreach ($array as $key => $value) {
if (Is_array ($value)) {
Array2xml ($value, $xml->addchild ($key));
}else{
$value =utf8_encode ($value);

if (Preg_match ("/([X81-xfe][x40-xfe])/", $value, $match)) {
$value = Iconv (' GBK ', ' utf-8 ', $value); Determine if any Chinese characters appear
}
$xml->addchild ($key, $value);
}
}
return $xml->asxml ();
}

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.