解决php array数组生成xml文件汉字编码问题
汉字在php应用中经常会给我们带来一些麻烦,今天在网上找到一段array数组转换成xml时发现汉字就为空了,后来gg了关天得出比较好的结果了,下面与大家分享,在 php 数组转xml我们在php中学会这样来写:
<?php
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);
?>当内容出现汉字时会出现为空的情况,解决办法是转编码处理,代码如下:
<?php
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);
//判断是否有汉字出现
}
$xml->addChild($key, $value);
}
}
return $xml->asXML();
}
?>
文章链接:http://www.phprm.com/shuzu/fs828.html
随便收藏,请保留本文地址!