簡體   English   中英

如何在PHP中使用UTF-8:json_encode

[英]how to use UTF-8 in PHP:json_encode

我正在從MySQL獲取數據並使用php以json格式顯示,但是我的數據是波斯語言,它顯示? 字符,而不是下面給出的原始數據。

{“ allnews”:[{“ id”:“ 35”,“ Onvan”:“ ???? ???? ????? ?????? ?????? ??? ??? ???? ????“},{” id“:” 36“,” Onvan“:” ?????????? ???? ?????????????????????? ??“},{” id“:” 37“,” Onvan“:”“ ????????????????????????????????????????????? ????? ???? ??????? ??? ?????? ????????? ??“},{” id“:” 38“,” Onvan“ :“ ????? ????????? ???? ??? ?? ?? ??????? ????????“},{“ID”: “ 39”,“ Onvan”:“ ??? ???? ??? ????”}}}

這是我的代碼。請您檢查哪里出錯了。

<?php
$hostname='localhost';
$username='xxxxxxxxx';
$password='xxxxxxxxx';
$response = array();
try {

    $dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

    $response["allnews"] = array();

    /*** QUERY ****/
    $sql='SELECT * FROM test';

    $stmt=$dbh->query($sql);

    $objs = $stmt->fetchAll(PDO::FETCH_OBJ);

    foreach($objs as $object) {
        $news = array();        
        $news["id"]=$object->id;
        $news["Onvan"]=$object->title;

        array_push($response["allnews"], $news);
    }

    echo json_encode($response);

    /*** close connection ***/
    $dbh=null;

}catch(PDOException $e) {
 echo $e->getMessage();
}
?>

采用

header("Content-type: application/json; charset=utf-8");

就在之前

echo json_encode($response);

而且也可能是Mysql Fetching Error

所以更換線

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest;charset=utf8",$username  ,$password);

最佳而簡單的解決方案

$dbh=new PDO("mysql:host=$hostname;dbname=dbtest",$username  ,$password);

將字符集添加到上面的行,例如(mysql:charset = utf8mb4;)

$dbh=new PDO("mysql:charset=utf8mb4;host=$hostname;dbname=dbtest",$username  ,$password);

您可以使用utf8_encode(String)

foreach($objs as $object) {
        $news = array();        
        $news["id"]=utf8_encode( $object->id);
        $news["Onvan"]=utf8_encode( $object->title);

        array_push($response["allnews"], $news);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM