Home php教程 php手册 php 生成xml文件汉字中文编码问题

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

May 25, 2016 pm 04:42 PM
php generate xml

今天在利用php做一个交互时我需要生成xml文档,但是发现xml中汉字全部乱码了,下面小编来给各位同学介绍一下此问题解决办法.

先看一个把数组转换xml,代码如下:

function array2xml($array, $xml = false){  
    if($xml === false){  
        $xml = new SimpleXMLElement(&#39;<root/>&#39;);  
    }  
    foreach($array as $key => $value){  
        if(is_array($value)){  
            array2xml($value, $xml->addChild($key));  
        }else{  
            $xml->addChild($key, $value);  
        }  
    }  
    return $xml->asXML();  
}  
 
header(&#39;Content-type: text/xml&#39;);  
print array2xml($array);
Copy after login

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

/*  
php 数组转换成xml  
*/ 
   
function array2xml($array, $xml = false){  
    if($xml === false){  
        $xml = new SimpleXMLElement(&#39;<root/>&#39;);  
    }  
    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(&#39;gbk&#39;, &#39;utf-8&#39;, $value);   //判断是否有汉字出现  
            }  
            $xml->addChild($key, $value);  
        }  
    }  
    return $xml->asXML();  
}
Copy after login


文章网址:

随意转载^^但请附上教程地址。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)