Home >php教程 >php手册 >PHP读取mssql2008,json数据中文乱码

PHP读取mssql2008,json数据中文乱码

WBOY
WBOYOriginal
2016-06-13 10:58:231333browse

PHP及网页使用UTF-8编码,数据库是sql server2008,使用默认编码(936,即GBK编码)
当读取数据库数据时,使用php自带的json_encode()返回到前端,结果中文不显示。

解决办法:

 

employeeGet.php 
<?php     
    header("Content-Type: text/html;charset=utf-8"); 
    //告诉浏览器不要缓存数据  
    header("Cache-Control: no-cache");   
     
    require "../conn.php"; 
    require "../share/json_gbk2utf8.php"; 
 
    $query = &#39;SELECT  
                seq, 
                employeeID, 
                employeeName, 
                department, 
                position, 
                sex, 
                birthday, 
                entryTime, 
                description, 
                convert(varchar(20),createTime,120) as createTime,<SPAN style="COLOR: #ff0000">//这里要注意,因为mssql2008的datetimne类型是带有毫秒的,直接在前端显示  
可能会有问题,所以要做一次转换</SPAN> 
                convert(varchar(20),updateTime,120) as updateTime                            
            FROM employees&#39;;     
    $arr = Array(); 
    $query = iconv("utf-8", "gbk//ignore", $query);//为了解决中文乱码问题  
    if($result = sqlsrv_query($conn, $query)){ 
        while($row = sqlsrv_fetch_array($result)){ 
            $arr[] = $row;           
        } 
    } 
    $data = JSON($arr); 
//  file_put_contents("E:/mylog.log", "JSON:".$data."\r\n", FILE_APPEND);     
    echo $data; 
?> 

employeeGet.php
<?php 
 header("Content-Type: text/html;charset=utf-8");
 //告诉浏览器不要缓存数据
 header("Cache-Control: no-cache"); 
 
 require "../conn.php";
 require "../share/json_gbk2utf8.php";

 $query = &#39;SELECT
    seq,
    employeeID,
    employeeName,
    department,
    position,
    sex,
    birthday,
    entryTime,
    description,
    convert(varchar(20),createTime,120) as createTime,//这里要注意,因为mssql2008的datetimne类型是带有毫秒的,直接在前端显示
可能会有问题,所以要做一次转换
    convert(varchar(20),updateTime,120) as updateTime       
   FROM employees&#39;; 
 $arr = Array();
 $query = iconv("utf-8", "gbk//ignore", $query);//为了解决中文乱码问题 
 if($result = sqlsrv_query($conn, $query)){
  while($row = sqlsrv_fetch_array($result)){
   $arr[] = $row;   
  }
 }
 $data = JSON($arr);
//  file_put_contents("E:/mylog.log", "JSON:".$data."\r\n", FILE_APPEND); 
 echo $data;
?>

 

? //json_gbk2utf8.php 
/**************************************************************
*为了实现对含有中文字符的数组进行json编码
*
*  使用特定function对数组中所有元素做处理
*  @param  string  &$array     要处理的字符串
*  @param  string  $function   要执行的函数
*  @return boolean $apply_to_keys_also     是否也应用到key上
*  @access public
*
*************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
    static $recursive_counter = 0;
    if (++$recursive_counter > 1000) {
        die('possible deep recursion attack');
    }
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            arrayRecursive($array[$key], $function, $apply_to_keys_also);
        } else {
//          file_put_contents("E:/mylog.log", "原始:".$value."\r\n", FILE_APPEND); 
            $value = iconv("gbk//ignore", "utf-8", $value);
//          file_put_contents("E:/mylog.log", "utf-8:".$value."\r\n", FILE_APPEND); 
            $array[$key] = $function($value);
//          file_put_contents("E:/mylog.log", "urlencode:".$array[$key]."\r\n", FILE_APPEND); 
        }

        if ($apply_to_keys_also && is_string($key)) {
            $new_key = $function($key);
            if ($new_key != $key) {
                $array[$new_key] = $array[$key];
                unset($array[$key]);
            }
        }
    }
    $recursive_counter--;
}

/**************************************************************
*
*  将数组转换为JSON字符串(兼容中文)
*  @param  array   $array      要转换的数组
*  @return string      转换得到的json字符串
*  @access public
*
*************************************************************/
function JSON($array) {
    arrayRecursive($array, 'urlencode', true);
    $json = json_encode($array);
    return urldecode($json);
}
/*
$array = array
(
        'Name'=>'希亚',
        'Age'=>20
);


echo JSON($array);
*/
?>

//json_gbk2utf8.php
/**************************************************************
*为了实现对含有中文字符的数组进行json编码
*
*  使用特定function对数组中所有元素做处理
*  @param  string  &$array     要处理的字符串
*  @param  string  $function   要执行的函数
*  @return boolean $apply_to_keys_also     是否也应用到key上
*  @access public
*
*************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
{
static $recursive_counter = 0;
if (++$recursive_counter > 1000) {
  die('possible deep recursion attack');
}
foreach ($array as $key => $value) {
  if (is_array($value)) {
   arrayRecursive($array[$key], $function, $apply_to_keys_also);
  } else {
//    file_put_contents("E:/mylog.log", "原始:".$value."\r\n", FILE_APPEND);
   $value = iconv("gbk//ignore", "utf-8", $value);
//    file_put_contents("E:/mylog.log", "utf-8:".$value."\r\n", FILE_APPEND);
   $array[$key] = $function($value);
//    file_put_contents("E:/mylog.log", "urlencode:".$array[$key]."\r\n", FILE_APPEND);
  }

  if ($apply_to_keys_also && is_string($key)) {
   $new_key = $function($key);
   if ($new_key != $key) {
    $array[$new_key] = $array[$key];
    unset($array[$key]);
   }
  }
}
$recursive_counter--;
}

/**************************************************************
*
*  将数组转换为JSON字符串(兼容中文)
*  @param  array   $array      要转换的数组
*  @return string      转换得到的json字符串
*  @access public
*
*************************************************************/
function JSON($array) {
arrayRecursive($array, 'urlencode', true);
$json = json_encode($array);
return urldecode($json);
}
/*
$array = array
(
  'Name'=>'希亚',
  'Age'=>20
);


echo JSON($array);
*/

 

这样,sql server 2008中的中文就可以在网页正常显示了。

如果要将中文正常插入到sql server 2008中,还要加入一条代码:$query = iconv("utf-8", "gbk//ignore", $query);//为了解决中文乱码问题

完整代码如下 :

<?php  
    /**
     * 如果员工编号在MySql中不存在则在MySql中插入员工记录
     * 如果该员工编号已经存在则进行更新操作
     */ 
    //如果用JSON格式则要使用text/html,不能使用text/xml  
    header("Content-Type: text/html;charset=utf-8"); 
//  header("Content-Type: text/html;charset=GBK");  
    //告诉浏览器不要缓存数据  
    header("Cache-Control: no-cache"); 
     
    require &#39;../conn.php&#39;; 
    $seq = $_POST["seq"]; 
    $employeeID = $_POST["employeeID"]; 
    $employeeName = $_POST["employeeName"]; 
    $department = $_POST["department"]; 
 
    if(!isset($seq) || $seq == ""){//seq不存在则插入新记录  
        $query = "INSERT INTO employees (employeeID, employeeName, department,  
                    createTime, updateTime) 
                VALUES (N&#39;$employeeID&#39;,N&#39;$employeeName&#39;,N&#39;$department&#39;,  
                    getdate(), getdate())"; 
    }else{//如果seq已存在则更新已有记录  
        $query = "UPDATE employees SET employeeID=&#39;$employeeID&#39;,  
                employeeName=&#39;$employeeName&#39;,department=&#39;$department&#39;, 
                updateTime=getdate()   
            WHERE seq=&#39;$seq&#39;"; 
    } 
     
//  file_put_contents("E:/mylog.log", $query."\r\n",FILE_APPEND);//用于调试  
    <SPAN style="COLOR: #ff0000">$query = iconv("utf-8", "gbk//ignore", $query);//为了解决中文乱码问题</SPAN> 
    if($result = sqlsrv_query($conn, $query)){ 
        echo true; 
    }else{ 
        echo false; 
    } 
//  echo $query;  
?> 

<?php
 /**
  * 如果员工编号在MySql中不存在则在MySql中插入员工记录
  * 如果该员工编号已经存在则进行更新操作
  */
 //如果用JSON格式则要使用text/html,不能使用text/xml
 header("Content-Type: text/html;charset=utf-8");
//  header("Content-Type: text/html;charset=GBK");
 //告诉浏览器不要缓存数据
 header("Cache-Control: no-cache");
 
 require &#39;../conn.php&#39;;
 $seq = $_POST["seq"];
 $employeeID = $_POST["employeeID"];
 $employeeName = $_POST["employeeName"];
 $department = $_POST["department"];

 if(!isset($seq) || $seq == ""){//seq不存在则插入新记录
  $query = "INSERT INTO employees (employeeID, employeeName, department,
     createTime, updateTime)
    VALUES (N&#39;$employeeID&#39;,N&#39;$employeeName&#39;,N&#39;$department&#39;,
     getdate(), getdate())";
 }else{//如果seq已存在则更新已有记录
  $query = "UPDATE employees SET employeeID=&#39;$employeeID&#39;,
    employeeName=&#39;$employeeName&#39;,department=&#39;$department&#39;,
    updateTime=getdate() 
   WHERE seq=&#39;$seq&#39;";
 }
 
//  file_put_contents("E:/mylog.log", $query."\r\n",FILE_APPEND);//用于调试
 $query = iconv("utf-8", "gbk//ignore", $query);//为了解决中文乱码问题
 if($result = sqlsrv_query($conn, $query)){
  echo true;
 }else{
  echo false;
 }
//  echo $query;
?>

 

 

Statement:
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