今天在利用php做一个交互时我需要生成xml文档,但是发现xml中汉字全部乱码了,下面小编来给各位同学介绍一下此问题解决办法.
先看一个把数组转换xml,代码如下:
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 数组转换成xml
*/
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();
}文章网址:
立即学习“PHP免费学习笔记(深入)”;
随意转载^^但请附上教程地址。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号