PHP: JSON output empty because of german char - php

There are a lot of topics who discuss my problem but I cant still solve it.
I have a database which I encode by JSON. But when I put content with german char like ä, ö, ü etc the output is empty.
Here is my php script:
<?PHP
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Verbindung zur Datenbank
include "inc_mysql.php";
//SQL-String
$select = "SELECT * FROM module ORDER BY name ASC";
//SQL-Befehl in Variable speichern
$sql = mysql_query($select);
//********************this one was missing!********************
mysql_set_charset("utf8");
//Array erstellen
$jsonArray = array();
while ($row = mysql_fetch_array($sql)){
$jsonArray[] = $row;
}
echo json_encode($jsonArray, JSON_UNESCAPED_UNICODE);
?>
The php file is UTF-8 without BOM.
The column is the dabase is utf8_general_ci.
BTW: The error reporting just says something about mysql_query() is depricated.
Might be a easy game for you guys :)
Solution found! Check the code!

You can use json_last_error_msg() function to show the error message. http://php.net/manual/en/function.json-last-error-msg.php
This function mb_convert_encoding() may help you.

Related

Why does the replacement character keeps appearing when echoing variable?

I'm creating a test application and keeping the name of the person who is taking it on a table, along with the answers. The problem lies when I enter the following characters
á é í ó ú ñ
I've tried some methods (like iconv function) but still not working.
//A sample of the code
require('../connect_db.php');
setlocale(LC_ALL,"es_ES");
mysql_query("SET NAMES 'utf8'");
$sql = "SELECT *
FROM database.test";
$result = mysql_query($sql) or die (mysql_error());
$row = mysql_fetch_array($result);
$name = utf8decode($row[1]);
echo mb_detect_encoding($name); //Just to test
echo $name;
The result:
UTF-8 G�mez
Edit: The problem is not on the database. I've manually entered names with these characters with no problem, so it must be the code.
SOLVED
There was no need to run the first utf8decode() when assigning values to $name
Instead I just called the function at the echo

Select hebrew from mysql database

honestly I am coming here after trying everything I could find online in order to fix that problem but nothing worked..
I have a phpmyadmin database table that encoded to utf_general_ci, when I insert data in Hebrew into it it works fine and I can see the Hebrew in the table on PhpMyAdmin, but when I need to retrieve the Hebrew data from the table that's when the problem starts...
right now I am using a simple sql query to select data from the table and I tried every code that should fix it I could find online but nothing seems to work.
my current code is:
<?php
$db = "android";
$username = "root";
$password = "";
$host = "localhost";
$sql = "select * from sample;";
$conn = mysqli_connect($host,$username,$password,$db);
$conn->set_charset('utf8');
$result = mysqli_query($conn,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array($row[0],$row[1]));
}
$str = json_encode(array($response));
echo $str;
mysqli_close($conn);
?>
and the output of the Hebrew word is \u05d4\u05d9\u05d9 what seems like a different encoding, my php file is encoded to UTF-8 and I am using npp to write it.
please try helping me out on this one cause I couldn't find an answer
This is a json_encode() behaviour, by default Unicode char are escaped as \u...
Try with JSON_UNESCAPED_UNICODE flag :
<?php
echo json_encode($arr, JSON_UNESCAPED_UNICODE);

json_encode error for russian characters

I am having trouble with the output of json_encode. I need to output Russian characters.
In my database table only Russian characters. In the output I am getting only "????????" question marks replaced Russian characters. I read many similar questions but none of them offered a real solution. I tried the following but none of them helped.
Below is my php code.
added ``header ('Content-type: application/json; charset=utf-8');`
used json_encode($albums, JSON_UNESCAPED_UNICODE);
tried mb_convert_encoding($str, 'UTF-8', 'auto');
json_encode($albums, JSON_UNESCAPED_UNICODE);
<?php
$host ="localhost";
$user ="misollar_user";
$pass="12345";
$db="misollar_db";
header ('Content-type: application/json; charset=utf-8');
$con = mysqli_connect($host,$user,$pass,$db);
$query = "select * from albums;";
$result = mysqli_query($con, $query);
$albums = array();
while ($row = mysqli_fetch_array($result)){
array_push($albums,array('id'=>$row[0], 'name'=>$row[1], 'songs_count'=>$row[2]));
}
mysqli_close($con);
echo json_encode($albums, JSON_UNESCAPED_UNICODE);
?>
You need to set UTF8 before retrieving results from mysql.
Just before you retrieve results from albums table, fire below query:
mysqli_query($con, 'SET names UTF8');
After this you can fetch your album results:
$query = "select * from albums;";
$result = mysqli_query($con, $query);

PHP json_encode is returning local language characters as html entities. Output needed in unicode

My php web service uses json_encode to return json data fetched from MySQL database table. The data should be returned in whatever local language as unicode. Instead local characters like hindi/telugu/bengali are displayed as html entities. But output is needed as unicode and NOT html entities.
<?php
//header('Content-Type: text/html;charset: utf8'); //wasted code line
//Connection and credentials
$servername = "xxx.yyy.zzz.nnn";
$username = "username";
$password = "password";
$dbname = "mydb";
//variables to store fetched data
$item[]=array();
$dataArray[] = array();
// Create connection
$conn = mysql_connect($servername, $username, $password);
//mysql_set_charset('utf8', $conn); //wasted code line
$mytopid = mysql_real_escape_string($_GET['mytopid']); //get input
$query = "SELECT * FROM datamaster where Id > '$mytopid' order by Id desc"; //Now query
//mysql_query("set names 'utf8'"); //wasted code line
if ($result=mysql_query($query,$conn)){
$rows = mysql_numrows($result);
$i= 0;
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//wasted code lines
//$dataArray[$i]["shortid"] = utf8_encode($row['Id']);
//$dataArray[$i]["shorttitle"] = utf8_encode($row['Title']);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
$dataArray[$i]["shorttitle"] = $row['Title'];
$i++;
}
$item[0]["response"] = 1;
$item[1]["matching"] = $rows;
$item[2]["events"]=$dataArray;
echo json_encode($item);
}else{
$item[0]["response"] = 0;
}
//echo json_encode($item, JSON_HEX_TAG| JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); //wasted code line
mysql_close($conn);
?>
Got Output:
Actual Output
Required Output:
[{"shortid":"5","shorttitle":"\u0c38\u0c32\u0c4d\u0c2e\u0c3e\u0c28\u0c4d\u200c \u0c05\u0c21\u0c3f\u0c17\u0c3f\u0c28\u0c3e \u0c05\u0c35\u0c15\u0c3e\u0c36\u0c2e\u0c3f\u0c35\u0c4d\u0c35\u0c32\u0c47\u0c26\u0c41!"}]
I finally convert it at my client program decode to local language.
The required output is supposed to be the default behaviour of json_encode. Despite most trials per php documentation (see the commented CODE lines that show my trials //wasted code line) the output continues to be in html entities except for English language.
My client programming language does not translate html entities.
Is there a php way to get the required output?
I have tried every possible concept on stack overflow and in php documentation. Now I need help.
Please refer to my database language settings
Use json_encode($item, JSON_UNESCAPED_UNICODE);. It will encode multibyte characters literally.
You can get more info here.
Actually it's strange your client side cannot handle escaped characters. What do you use exactly?
Thnak you Wazelin for the prompt reply. I had tried the JSON_UNESCAPED_UNICODE approach too earlier. But that output continued to be html entities.
A temporary fix to the problem I have incidentally tumbled in to using html_entity_decode.
I changed the code lines in while loop to:
while ($i < $rows){
//fetch data
$row = mysql_fetch_array($result);
//reality
$dataArray[$i]["shortid"] = $row['Id'];
//handle html entities of local language
$dataArray[$i]["shorttitle"] = html_entity_decode($row['Title']);
$i++;
}
That had given the required output.
But doing this to every single web service is not like an ideal solution.
Quite strangely the default json_encode behaviour is very elusive in my case.
Check documentation:
http://php.net/manual/en/function.json-encode.php
There are some options which allows you to encode your data correctly.

How to get rid of json_encode(): Invalid UTF-8 sequence in php?

I am getting this warning and the php returns null .
PHP Warning: json_encode(): Invalid UTF-8 sequence in argument in
/var/www/rreadyreckoner/get_instruction.php on line 26
{"result":[{"instruction":null}]}
I am trying to run this php script.
<?php
include "demo_config.php";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$query ="SELECT instruction FROM `rreadyreckoner` ORDER BY id DESC LIMIT 1;";
$res = mysqli_query($con,$query);
$result = array();
while($row = mysqli_fetch_array($res))
{
array_push($result,
array('instruction'=>$row[0]));
}
if(!$result)
{
echo "Nothing to display";
}else
{
echo json_encode(array("result"=>$result));
}
mysqli_close($con);
?>
The only change I did was when inserting content into mysql database removed a character that was getting inserted by default and replaced it with nothing.
$instruction =$_POST["instruction"];
$plainHTML = str_replace(chr(194),"",$instruction);
$sql = "INSERT INTO rreadyreckoner (id, instruction)
VALUES (NULL, '$plainHTML')";
Before doing this I was getting a proper response.
Any help or suggestion is appreciated. Thank you.
Simply add this:
mysqli_set_charset($con, "utf8");
after mysql connect.
$t = json_encode($s, JSON_UNESCAPED_UNICODE);
avoids the \u.... stuff.
Don't use mb_encode, etc.
194 is hex C2 which is a common first byte in utf8 sequences.
See Trouble with utf8 characters; what I see is not what I stored for more discussion on what needs to be done. In particular, check the SELECT HEX... technique to see if data is stored correctly.
Back to the title... Can you provide the invalid sequence you are dealing with? You can do something like echo bin2hex(...) to get the hex of the naughty string.

Categories