简体   繁体   中英

how to use UTF-8 in PHP:json_encode

I am getting data from MySQL and displaying in json format using php but my data are in Persian language and it show ? character instead of the original data like given below.

{"allnews":[{"id":"35","Onvan":"???? ???? ????? ????? ?????? ?? ??? ?????"},{"id":"36","Onvan":"?????????? ???? ? ??????????? ?????"},{"id":"37","Onvan":" ??????? ???? ??? ??? ???? ???? ?? ??? ?? ???? ???? ??????? ??? ?????? ???????? ?? "},{"id":"38","Onvan":" ????? ????????? ???? ??? ?? ?? ??????? ????????"},{"id":"39","Onvan":"??? ???? ??? ????"}]}

Here is my code .Can you please check where has it gone wrong.

<?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();
}
?>

Use

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

Just before

echo json_encode($response);

And It also may be Mysql Fetching Error

So replace line

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

with

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

Best and simple solution

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

add charset to above line like ( mysql:charset=utf8mb4; )

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

You can use 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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM