一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php 生成xml文件汉字中文编码问题

时间:2013-11-04 编辑:简简单单 来源:一聚教程网


先看一个把数组转换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);

这样如果没有中文汉字没问题

如果有中文就有问题了当内容出现汉字时会出现为空的情况,解决办法是转编码处理

 

 代码如下 复制代码
/*
php 数组转换成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);   //判断是否有汉字出现
            }
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}

热门栏目