Today, when I use php for interaction, I need to generate xml documents, but I found all Chinese characters in xml are garbled. the following small series will introduce the solutions to this problem. first, let's look at a code that converts an array into xml. the code is as follows: functionar... today, when I use php for interaction, I need to generate xml documents, but I found all Chinese characters in xml are garbled. the following small series will introduce the solutions to this problem.
First, let's look at the code for converting arrays into xml:
function array2xml($array, $xml = false){ if($xml === false){ $xml = new SimpleXMLElement('
'); } 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);
In this way, if there are no Chinese characters, there will be a problem if there is a problem with Chinese characters. when there is a problem with Chinese characters in the content, it will be empty. the solution is to convert the code into the following:
/* Convert the php array to xml */function array2xml ($ array, $ xml = false) {if ($ xml = false) {$ xml = new SimpleXMLElement ('
');} 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 ();}
Article URL:
Reprint ^ at will, but please attach the tutorial address.