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

Source: Internet
Author: User
Tags foreach addchild

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.