Solve the problem of generating Chinese character encoding for xml files using php array

Source: Internet
Author: User

Chinese characters often bring us some trouble in php applications. Today, when I find an array on the Internet and convert it into xml, I find that the Chinese characters are empty. Then gg gets a better result after shutting down the sky, I would like to share with you the following.

In php array to xml, we learned to write this in php.

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 );

If the content contains Chinese characters, it is null.


Solution: Transcoding

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 {

// $ Value = utf8_encode ($ value );

If (preg_match ("/([x81-xfe] [x40-xfe])/", $ value, $ match )){
$ Value = iconv ('gbk', 'utf-8', $ value );
// Determine whether there are any Chinese Characters
}
$ Xml-> addChild ($ key, $ value );
}
}
Return $ xml-> asXML ();
}

Here are some examples of Chinese Character regular expressions.

1. Determine whether the string is full of Chinese Characters

The Code is as follows: Copy code

<? Php
$ Str = 'all are Chinese Character test ';
If (preg_match_all ("/^ ([x81-xfe] [x40-xfe]) + $/", $ str, $ match )){
Echo 'all Chinese characters ';
} Else {
Echo 'all Chinese characters ';
}
?>

When $ str = 'all are Chinese Character test', the output "All are Chinese characters ";
When $ str = 'all is a Chinese character test', the output is "Not all Chinese characters ";

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.