PHP及網頁使用UTF-8編碼,數據庫是sql server2008,使用默認編碼(936,即GBK編碼)
當讀取數據庫數據時,使用php自帶的json_encode()返回到前端,結果中文不顯示。
解決辦法如下:
這樣,sql server 2008中的中文就可以在網頁正常顯示了。
如果要將中文正常插入到sql server 2008中,還要加入一條代碼:$query = iconv("utf-8", "gbk//ignore", $query);//為了解決中文亂碼問題
完整代碼如下 :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<?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 '../conn.php' ; $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 '$employeeID' ,N '$employeeName' ,N '$department' , getdate (), getdate ())"; } else { //如果seq已存在則更新已有記錄 $query = "UPDATE employees SET employeeID= '$employeeID' , employeeName= '$employeeName' ,department= '$department' , updateTime= getdate () WHERE seq= '$seq' "; } // 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讀取mssql json數據中文亂碼的解決辦法,希望對大家有所幫助!