2016-02-24 33 views
-1

我嘗試通過json在php中編碼mysql阿拉伯文數據,當print_r選定數據的數組顯示阿拉伯文正確,但是當json編碼這個數組返回阿拉伯文與空 這是我的頭php json編碼返回阿拉伯語windows-1256字符集與空

header('Content-type:application/json;charset=windows-1256'); 

這是我的查詢

$que=mysqli_query($con,"SELECT * from cat"); 
while($res=mysqli_fetch_array($que)){ 
    $arr[]=array(
     'id' => $res['catid'], 
     'name' => $res['name'] 
    ); 
} 
echo json_encode($arr); 

的print_r $改編

[0] => Array 
    (
     [id] => 1 
     [name] => العاصمة 
    ) 

[1] => Array 
    (
     [id] => 2 
     [name] => حولي 
    ) 

json_encode($ ARR)

{ 
"id": "1", 
"name": null 
}, 
{ 
"id": "2", 
"name": null 
}, 

這是我的數據庫 my database

+0

[使用UTF-8](http://stackoverflow.com/a/279279/1064767) – Sammitch

+0

猜猜它可能與非UTF-8字符集有關。 'json_last_error()'給你什麼?見http://php.net/manual/en/function.json-last-error.php? – fateddy

+0

返回'5'.......... – user3718167

回答

0

這是對JSON specification

JSON文本將以UTF-8編碼,UTF-16,或UTF-32。默認的 編碼是UTF-8,以UTF-8編碼的JSON文本是 可互操作的,因爲它們將被最大數量的實現成功讀取;有許多實現 無法成功讀取其他編碼中的文本(如UTF-16和 UTF-32)。

雖然您當然可以生成類似於JSON的輸出並使用其他編碼(如Windows-1256),但它不會是實際的JSON,因此您無法使用JSON庫或工具對其進行編碼或解碼。

除非你有非常充分的理由產生這種無效的JSON,只需按照阻力最小的路徑:

header('Content-type:application/json'); 
$que = mysqli_query($con,"SELECT * from cat"); 
while ($res = mysqli_fetch_array($que)) { 
    $arr[] = array(
     'id' => $res['catid'], 
     'name' => is_null($res['name']) ? null : mb_convert_encoding($res['name'], 'UTF-8', 'WINDOWS-'1256) 
    ); 
} 
echo json_encode($arr); 
+0

錯誤::: mb_convert_encoding():指定的非法字符編碼 – user3718167

+0

感謝所有如果在這裏找到我的答案http://stackoverflow.com/questions/35525502/how-to-use-php-json-encode -without-utf8 – user3718167

+0

未對代碼進行測試,只需從中獲取想法即可。 (mb _...接受的名稱可能是'Win-1256','CP1256'或類似的東西。) –