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