Sunny Sultan
Sunny Sultan

Reputation: 1180

JSON encode error for bengali fonts

Everything is working fine. But when I try to encode some Bengali font from mysql database problem occurred that time. Bengali fonts are displayed as "?????????????".

** Php file **

<?php 
define('HOST','localhost');
define('USER','xxxxxxx');
define('PASS','xxxxxxxx');
define('DB','xxxxxxxxx');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "select * from bookinfo ORDER BY ID DESC";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
    'name'=>$row[1],
    'writter'=>$row[2],
    'url'=>$row[3]
     ));
}

echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);

mysqli_close($con);

?>

click here to see output result

Upvotes: 1

Views: 2387

Answers (2)

Khushboo
Khushboo

Reputation: 475

first set content type eg. header('Content-Type: application/json; charset=utf-8')

then set utf-8 code before execute your query

Like this:

<?php
header('Content-Type: application/json; charset=utf-8');    
define('HOST','localhost');
define('USER','xxxxxxx');
define('PASS','xxxxxxxx');
define('DB','xxxxxxxxx');    
$con = mysqli_connect(HOST,USER,PASS,DB);    
mysqli_query($con,"SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");

$sql = "select * from bookinfo ORDER BY ID DESC";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_row($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'writter'=>$row[2],
'url'=>$row[3]
));
}   
echo json_encode(array("result"=>$result), JSON_UNESCAPED_UNICODE);    
mysqli_close($con);    
?>

It will give you correct font as you expected.

Upvotes: 12

Mangesh Sathe
Mangesh Sathe

Reputation: 2177

 header('Content-Type: application/json; charset=utf-8');

Upvotes: 2

Related Questions