Chinese character encoding in xml file generated by php

Source: Internet
Author: User
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.

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.