I can not manage to see all the lines of my mysql query result returned as JSON Object using JSON_encode() php function.
Here is my code :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne = array();
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID']
);
$bilan[$ligne['User']] = $ligne[[
['User_ID'][$rowr['User_ID']]
]];
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It returns me :
{"":null,"0":{"User_ID":"1"},"1":{"User_ID":"19"},"2":{"User_ID":"78"},"3":{"User_ID":"79"},"4":{"User_ID":"85"},"5":{"User_ID":"86"},"6":{"User_ID":"87"},"7":{"User_ID":"88"},"8":{"User_ID":"91"},"9":{"User_ID":"92"},"10":{"User_ID":"93"},"11":{"User_ID":"94"},"12":{"User_ID":"95"},"13":{"User_ID":"96"},"14":{"User_ID":"97"},"15":{"User_ID":"98"},"16":{"User_ID":"99"},"17":{"User_ID":"100"},"18":{"User_ID":"101"},"19":{"User_ID":"102"},"20":{"User_ID":"103"},"21":{"User_ID":"104"},"22":{"User_ID":"105"},"23":{"User_ID":"106"},"24":{"User_ID":"107"},"25":{"User_ID":"108"},"26":{"User_ID":"109"},"27":{"User_ID":"110"},"28":{"User_ID":"111"},"29":{"User_ID":"112"},"30":{"User_ID":"113"},"31":{"User_ID":"114"},"32":{"User_ID":"115"},"33":{"User_ID":"116"}}
Now, I am trying to associate the other fields of each record in the json output. But when adding this to me code, there is no more output.
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
$bilan[$ligne['User']] = $ligne[[
['User_ID'][$rowr['User_ID']]
][
['User_Nom'][$rowr['User_Nom']]
]];
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It seems like on numerical values can be displayed and not alpha characters.
Please help me mixing in the same output both numerical and alpha contents.
Thanks
Arnaud
$ligne['User'] is not initialised, could you try this:
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
I tested it with this code
$result[] = ['User_ID' => 1, 'User_Nom' => 'Nom1'];
$result[] = ['User_ID' => 2, 'User_Nom' => 'Nom2'];
$result[] = ['User_ID' => 3, 'User_Nom' => 'Nom3'];
$bilan = [];
while ($rowr = array_pop($result)) {
$ligne = array (
"User_ID" => $rowr['User_ID'],
"User_Nom" => $rowr['User_Nom']
);
array_push($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
It provides this result:
{"0":{"User_ID":3,"User_Nom":"Nom3"},"1":{"User_ID":2,"User_Nom":"Nom2"},"2":{"User_ID":1,"User_Nom":"Nom1"}}
Note the result has a different start, it does not contain
"":null,
any more. This was the result of the strange $bilan[undefined] = undefined line
Converted to PHP >= 5.5 for clarity.
I am guessing and making assumptions, but what else can I do? The main issue I see is that you may be tripping over your feet with the array syntax. It appears that you want to re-index the results by 'User_ID', which I assume is some string identifier found in each table record.
Modularized, in the procedural form ...
/*
Assuming you are attempting to re-index by the 'User_ID' field
of each record before encoding as JSON.
*/
function getDb($ip, $user, $password, $database) {
$db = mysqli_connect($ip, $user, $password, $database);
//error checking etc ...
return $db;
}
function selectRecords(mysqli $db, $sql) {
$result = mysqli_query($db, $sql);
if (!$result) {
throw new UnexpectedValueException("Database query (read) was unsuccessful!");
}
return $result;
}
function getUserRecords(mysqli $db) {
$query = 'SELECT * FROM Users';
return selectRecords($db, $query);
}
function reindexByField($newIndex, $userResults) {
$reindexed = [];
while ($row = mysqli_fetch_assoc($userResults)) {
if (!isset($row[$newInded])) {
throw new OutofBoundsException("The index '" . $newIndex . "' does not exist in the tested record");
}
$redindexed[$row[$newIndex]] = $row;
}
return $reindexed;
}
function getJsonFromArray(array $records) {
$json = json_encode($records, JSON_FORCE_OBJECT);
if (!$json) {
throw new UnexpectedValueException("Records were not encoded into a JSON formatted string. Got boolean false, instead.");
}
return $json;
}
In the procedural form, then ...
try {
$db = getDb($ip, $user, $password, $db); // Just pretend for a moment.
echo getJsonFromArray(reindexByField('User_ID', getUserRecords($db));
} catch (e) {
// Your handler code here.
} finally {
mysqli_close($db);
}
An object-oriented approach can make your code more organized.
You're right, since the orginal clean plan, because it was not working, I made too many modifications which finally added complexity where there is no need...
I found in php doc the possibility to learn more about the error generated when adding the other fields in the json conversion. json_last_error() was the key for understanding the issue.
So I added :
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - Aucune erreur';
break;
case JSON_ERROR_DEPTH:
echo ' - Profondeur maximale atteinte';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Inadéquation des modes ou underflow';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Erreur lors du contrôle des caractères';
break;
case JSON_ERROR_SYNTAX:
echo ' - Erreur de syntaxe ; JSON malformé';
break;
case JSON_ERROR_UTF8:
echo ' - Caractères UTF-8 malformés, probablement une erreur d\'encodage';
break;
default:
echo ' - Erreur inconnue';
break;
}
This returns me a UTF-8 encoding issue. So I modified my code adding some
utf8_encode($rowr['Fieldname'])
First working solution is very near from #PaulH one's, just, in my specific case, I definetely have to add (utf8_encode()) statement :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$ligne =array();
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array ("User_ID" => $rowr['User_ID'],
"User_Nom" => utf8_encode($rowr['User_Nom']),
"User_Prenom" =>utf8_encode($rowr['User_Prenom']));
array_push ($bilan, $ligne);
}
echo json_encode($bilan, JSON_FORCE_OBJECT);
and it now displays all the fields, all the lines. But there were still some "é" transformed to "\u00e9". So this post put the final brick to the solution.
I modified :
JSON_FORCED_OBJECT
to
JSON_UNESCAPED_UNICODE
as json_encode() parameter.
Finally, code delivering exactly what I want is the following :
$Sql_Query = "SELECT * FROM Users";
$result = mysqli_query($dbc,$Sql_Query);
$bilan = array();
while ($rowr = mysqli_fetch_assoc($result)) {
$ligne = array ("User_ID" => $rowr['User_ID'],
"User_Nom" => utf8_encode($rowr['User_Nom']),
"User_Prenom" =>utf8_encode($rowr['User_Prenom']));
array_push ($bilan, $ligne);
}
echo json_encode($bilan, JSON_UNESCAPED_UNICODE);
Related
I'm trying to create a dynamic swiper that is able to automatically update itself whenever I make changes in the database. The problem that I've encountered right now is that I've got 6 pictures and description in the swiper but all of them only retrieve from the first field from my database.
Old screenshot of the page. As you can see from the first screenshot I am able to retrieve the data which is the picture and the description from the database, but only repeatingly retrieve from the first field of the database for all the 6 results. Able to show it in the php area. Only the first slider is working when i called the function in html.
Any help would be appreciated, thank you.
<?php
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
for($i = 0;$i<mysqli_num_rows($result);$i++) {
//for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
$count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
$count = 0;
while($row = mysqli_fetch_assoc($result)) {
//while($row = fetch_array($result)) {
// Not needed as the output is the same
if($count == 0) {
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
$count++;
}
}
return $output;
}
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
?>
When working with databases use while instead of foreach. The problem you're having is that mysqli_result is not exactly what you think it is, You can have a look here:
https://www.php.net/manual/en/class.mysqli-result.php
Here is a clean version of the code provided. I didn't setup a db for this so to test the logic I implemented a dummy function to work on a set array. I hope the comments are helpful.
function fetch_array(&$array) {
// Grab the first value from the array
$return = current($array);
// remove the value we just grabbed
array_shift($array);
// if what we have is an array spit it out, else return false
return is_array($return) ? $return : false;
}
function make_query($connect) {
$query = "SELECT * FROM db.slider ORDER BY p_id ASC";
$result = mysqli_query($connect, $query);
return $result;
}
function make_slide_indicators($result) {
$output = '';
$count = 0;
//for($i = 0;$i<mysqli_num_rows($result);$i++) {
for($i = 0;$i<count($result);$i++) {
if ($i == 0) {
$output .= '<li data-target="#" data-slide-to="'.$i.'" class="active"></li>';
} else {
$output .= '<li data-target="#" data-slide-to="'.$i.'"></li>';
}
// $count++ === $count = $count + 1;
}
return $output;
}
function make_slides($result) {
$output = '';
// $count = 0;
//while($row = mysqli_fetch_assoc($result)) {
while($row = fetch_array($result)) {
// Not needed as the output is the same
//if($count == 0) { ... } else { ... }
$output .= '
<div class="swiper-slide platform">
<img src="'.$row["p_img"].'" alt="'.$row["p_name"].'" />
<div class="swiper-slide platform">
<h3>'.$row["p_desc"].'</h3>
</div>
</div>';
// Not used at the moment
// $count++;
}
return $output;
}
//$connect = mysqli_connect("localhost", "root", "", "db");
//$result = make_query($connect);
$result = [['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc'],['p_img' => 'img','p_name' => 'name','p_desc' => 'desc']];
echo make_slide_indicators($result);
echo PHP_EOL;
echo make_slides($result);
The biggest difference in the code is that we're using mysqli_num_rows() in make_slide_indicators(). We don't need to fetch all the data from the mysql result, we just need the number of rows we received.
That solves another problem. If you go trough the whole result with mysqli_fetch_assoc() the next time you would try to work on the same result you would only get the last value. The result has in internal pointer that moves a position forward when a line is read.
If you would ever want to go over a result more then once you'd need to use mysqli_data_seek(). Have a look here:
https://www.php.net/manual/en/mysqli-result.data-seek.php
If you run the code as is You'll see that the logic works correctly. If you still have an issue when you switch to the db connection the problem is there. Here's a quick debug check for you:
$connect = mysqli_connect("localhost", "root", "", "db");
$result = make_query($connect);
echo "Number of rows: ".mysqli_num_rows($result).PHP_EOL;
while($r = mysqli_fetch_assoc($result)) {
var_dump($r);
}
I am having 2 issues with the following if/elseif/else statement:
$rows = array();
$stmt = $dbconnection->query("SELECT * FROM TABLE_NAME WHERE data_field LIKE 'data_selection'");
if ($stmt) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
if ($row['something '] == 'selection1') {
$highlightsarray = array("gridHighlights" => 'text option 1 to display on site');
$highlights = $row + $highlightsarray;
} elseif ($row['something'] == 'selection2') {
$highlightsarray = array("gridHighlights" => 'text option 2 to display on site');
$highlights = $row + $highlightsarray;
} else {
$highlights = "<p>default messaging</p>";
}
$fields = $highlights; // this is a placeholder for other if statements I need to add
$output .= $modx->getChunk('chunk_name', $fields);
}
}
return $output;
}
The first issue I am having is that == is not returning any results, if I change that to = then it somewhat works.
If I make my statement ($row['something '] = 'selection1') (with just =), then it is only returning the first if condition, even if it is not true and should be returning either the elseif or else condition.
Not sure what I am doing wrong here, any assistance is greatly appreciated, thank you.
Closing this question, doing a var_dump as suggested and reviewing my strings got this working. Here is the final code used:
$rows = array();
$stmt = $dbconnection->query("SELECT * FROM TABLE_NAME WHERE data_field LIKE 'data_selection'");
if ($stmt) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
var_dump($row); // to review output
if ($row['something '] == NULL) {
$highlights = $row;
} elseif ($row['something'] == 'selection2') {
$highlightsarray = array("gridHighlights" => 'text option 2 to display on site');
$highlights = $row + $highlightsarray;
} elseif ($row['something'] == 'selection1') {
$highlightsarray = array("gridHighlights" => 'text option 1 to display on site');
$highlights = $row + $highlightsarray;
}
$fields = $highlights; // this is a placeholder for other if statements I need to add (like $fields = $highlights + $anotherIfStatement;)
$output .= $modx->getChunk('chunk_name', $fields);
}
}
return $output;
}
I have this code - it's not done by me :s and don't have time to replace the deprecated calls.
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
$db=mysql_connect('localhost','carros_mil1','K-Jw)ureB.}M');
mysql_select_db('carros_mil0',$db);
$nombreListModelo = 'modelo_'.str_replace(" ","_",strtolower($_REQUEST['nombreMarca']));
$sql = "SELECT DISTINCT (identificador) AS id
FROM modelos
WHERE nombre = '".$nombreListModelo."'";
$rs=mysql_query($sql);
$i=0;
while ($row = mysql_fetch_array($rs)) {
$vectorModelo[$i] = $row['id'];
$i++;
}
$sql = "SELECT attribute_id
FROM eav_attribute
WHERE attribute_code = '".$nombreListModelo."'";
$rs = mysql_query($sql);
$row = mysql_fetch_array($rs);
$id1 = $row['attribute_id'];
$sql= "SELECT eao.option_id AS option_id
FROM eav_attribute_option eao, eav_attribute_option_value eaov
WHERE eao.option_id=eaov.option_id AND attribute_id = ".$id1." ORDER BY eaov.value";
$rs=mysql_query($sql);
$retorno = array();
$bandera = true;
while ($row = mysql_fetch_array($rs)) {
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
if ($_REQUEST['bandera']=='vende') {
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
if (!is_null($row2['value'])) $retorno[$row2['value']] = $row2['value'];
else
if (!is_null($row2['option_id'])) $retorno[$row2['option_id']] = $row2['value'];
}
}
}
if($bandera)
$retorno[''] = 'Todos';
header('Content-Type: application/json');
//echo json_encode($retorno);
foreach($retorno as $k => $v) {
printf("%s => %s\n", $k, $v);
}
print_r($retorno);
echo json_encode($retorno);
Since I noticed something strange in the generated json, I added 2 different ways of printing the contents of the array.
The JSON way adds me a null:null entry. The strange case is that I'm checking !is_null($row2['value']) each time I add an element.
When I hit the url under certain parameters, I get:
Elantra => Elantra
Getz => Getz
H1 => H1
i-10 => i-10
New Accent => New Accent
Santa Fé => Santa Fé
Tucson => Tucson
Array
(
[Elantra] => Elantra
[Getz] => Getz
[H1] => H1
[i-10] => i-10
[New Accent] => New Accent
[Santa Fé] => Santa Fé
[Tucson] => Tucson
)
{"Elantra":"Elantra","Getz":"Getz","H1":"H1","i-10":"i-10","New Accent":"New Accent",null:null,"Tucson":"Tucson"}
The first 6 lines correspond to a custom print foreach loop. There's also a print_r call which only shows 6 elements. The 3rd form - which is the actual one I need - shows a null value.
So: Why is $retorno accepting null entries when I check the null condition beforehand? considering this script is full - no missing code here.
(Thanks #Hammerstein - don't know why you didn't write that as an answer).
The problem is that one of such values was not correctly being encoded, since it was not an ANSI value and was not encoded in UTF8. In this way, since "Santa Fé" had a "strange" character, it was encoded as null instead of "Santa F\u00e9".
Tip: Never assume your database is using an utf8_ charset
The solution was to explicitly encode the values when composing the array:
...
$bandera = false;
$sql2= "SELECT value, option_id
FROM eav_attribute_option_value
WHERE option_id = ".$row['option_id']."
ORDER BY value";
$rs2=mysql_query($sql2);
$row2= mysql_fetch_array($rs2);
//ENCODE the values to a good charset
$value = utf8_encode($row2['value']);
$option_id = utf8_encode($row['option_id'])
if ($_REQUEST['bandera']=='vende') {
$retorno[$value] = $value;
} else {
$existe=false;
for($k=0;$k<count($vectorModelo);$k++) {
if($row2['option_id'] == $vectorModelo[$k]) {
$existe=true;
break;
}
}
if($existe) {
if($_REQUEST['tipo']=='contactenos')
$retorno[$value] = $value;
else
$retorno[$option_id] = $value;
}
}
...
I just start to use php webservice.I want to take all data in 'urun' table just sending 'id' Here is my code and i dont know how to solve it.
if($_GET["function"] == "getUrun"){
if(isset($_GET["id"]) && $_GET["id"] != ""){
$id = $_GET["id"];
$kategoriid =$_GET["kategoriid"];
$urunadi =$_GET["urunadi"];
$urunfiyati =$_GET["urunfiyati"];
$aciklama =$_GET["aciklama"];
$where="";
$where = "id='".$id."' AND kategoriid='".$kategoriid."' AND urunadi='".$urunadi."' AND urunfiyati='".$urunfiyati."' AND aciklama='".$aciklama."'";
$result = mysql_query("SELECT * FROM urun WHERE ".$where."");
$rows = array();
if($r=mysql_fetch_assoc($result))
{
$rows[] = $result;
$data = json_encode($rows);
echo "{ \"status\":\"OK\", \"getUrun\": ".$data." }";
}else{
echo "{ \"status\":\"ERR: Something wrong hepsi\"}";}
}else{
echo "{ \"status\":\"ERR: Something wrongs hepsi\"}";}
}
It should be:
if ($result) {
$rows = array();
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('status' => 'OK', 'getUrun' => $rows));
} else {
echo json_encode(array('status' => 'ERR: Something wrong hepsi'));
}
You need to get all the results in an array, and then encode the whole thing. You should also use json_encode for the containing object, don't try to create JSON by hand.
My PHP script works fine, but for some element, i get null values whereas in the table the text is well here :
[
{
"etat":"online",
"nb_visiteurs":"0",
"id":"1",
"date_debut":"19\/05\/2014",
"prix":"40",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"2",
"date_debut":"21\/05\/2014",
"prix":"30",
"description":null,
"id_author":"1",
"titre":null
},
{
"etat":"offline",
"nb_visiteurs":"0",
"id":"3",
"date_debut":"22\/05\/2014",
"prix":"23",
"description":"TOP NOIR STYLE ASIATIQUE EN BON ETAT T 3\r\n\r\nFAIRE PROPOSITION",
"id_author":"1",
"titre":"Top noir style asiatique en bon etat t3"
},
{
"etat":"online",
"nb_visiteurs":"0",
"id":"4",
"date_debut":"22\/05\/2014",
"prix":"45",
"description":null,
"id_author":"1",
"titre":"Lit+sommier+matelas+ table de chevet+commode"
}
]
Here is the content of my annonces table :
And here is the structure of the table :
<?php
$PARAM_hote='aaaaaa';
$PARAM_port='3306';
$PARAM_nom_bd='bbbbbbbbb';
$PARAM_utilisateur='ccccccccc';
$PARAM_mot_passe='dddddddddd';
// Create connexion to BDD
$connexion = new PDO('mysql:host='.$PARAM_hote.';port='.$PARAM_port.';dbname='.$PARAM_nom_bd, $PARAM_utilisateur, $PARAM_mot_passe);
try {
// Getting username / password
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare SQL request to check if the user is in BDD
$result1=$connexion->prepare("select * from tbl_user where username = '".$username."' AND password = '".$password. "'");
$result1->execute();
// Getting all results in an array
$arrAllUser = $result1->fetchAll(PDO::FETCH_ASSOC);
// If the size of array is equal to 0, there is no user in BDD
if (sizeof($arrAllUser) == 0) {
echo "fail";
}
// In this case, a user has been found, create a JSON object with the user information
else {
// Getting id of the user
$id_user = $arrAllUser[0]['id'];
// Prepare a second SQL request to get all annonces posted by the user
$result2=$connexion->prepare(" select * from annonces where id_author = '".$id_user."' ");
$result2->execute();
// Getting all annonces posted by the user in an array
$arrAllAnnonces = $result2->fetchAll(PDO::FETCH_ASSOC);
// Set in key user the USER structure
$array['user'] = $arrAllUser[0];
// Set in key annonces all annonces from the user
$array['annonces'] = $arrAllAnnonces;
// JSON encore the array
$json_result = json_encode($array);
echo $json_result;
}
} catch(Exception $e) {
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
It's happening because french letters, the function fails to parse them.
try to use flag JSON_UNESCAPED_UNICODE
json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE)
you can play with the flags
try this
$output = array();
foreach ($array as $row)
{
$output[]=array_map("utf8_encode", $row);
}
$json_result = json_encode($output);
echo $json_result;
agree with volkinc answer,if you have a new php version you can use
json_unescaped_unicode instead of json_encode
and if your php version 5.3 and older unescaped wont work , just add this function at the bottom of the script and use it instead of json_encode
function my_json_encode($in) {
$_escape = function ($str) {
return addcslashes($str, "\v\t\n\r\f\"\\/");
};
$out = "";
if (is_object($in)) {
$class_vars = get_object_vars(($in));
$arr = array();
foreach ($class_vars as $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}elseif (is_array($in)) {
$obj = false;
$arr = array();
foreach($in AS $key => $val) {
if(!is_numeric($key)) {
$obj = true;
}
$arr[$key] = my_json_encode($val);
}
if($obj) {
foreach($arr AS $key => $val) {
$arr[$key] = "\"{$_escape($key)}\":{$val}";
}
$val = implode(',', $arr);
$out .= "{{$val}}";
}else {
$val = implode(',', $arr);
$out .= "[{$val}]";
}
}elseif (is_bool($in)) {
$out .= $in ? 'true' : 'false';
}elseif (is_null($in)) {
$out .= 'null';
}elseif (is_string($in)) {
$out .= "\"{$_escape($in)}\"";
}else {
$out .= $in;
}
return "{$out}";
}
and use my_json_encode instead of json_encode and dont forget this line :
header('content-type:text/html;charset=utf-8');
thanks to the person who made this function i forgot from where i got it.