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);
Related
I have a problem with json_encode, I have a database that is encoded in utf8mb4_unicode_ci which contains accented French characters.
when I do the select and I encode in json (json_encode) I have no display but when I remove the accents it works, if someone can help me.
Thanks
getData.php
<?php
include "connection.php";
//include "crypto.php";
header('Content-Type: application/json');
$stmt = $db->prepare("SELECT * FROM ec_product_categories");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
?>
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);
Problem
I am getting 0 results when searching for an Arabic word in a MySQL database using the SELECT query with PHP.
However, the same exact query yields results in alternative clients, namely SQLBuddy and the likes. Everything is encoded in UTF-8.
Code
<?php
$host = "localhost";
$username = "hans_wehr_client";
// i know my security is a joke :)
$password = "hans_wehr";
$database = "hans_wehr";
$conn = new mysqli($host, $username, $password, $database);
if ($conn == TRUE){
$search = $_GET["search"];
$encoded_search = utf8_encode($search);
echo $encoded_search."<br>";
header('Content-Type: text/html; charset=utf-8');
$sql = "SELECT * FROM dictionary WHERE ARABIC LIKE '$search'";
echo $sql."<br>";
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
header('Content-Type: text/html; charset=utf-8');
echo $row["ARABIC"]. " - Meaning: " . $row["ENGLISH1"]. " " . $row["ENGLISH2"]. "<br>";
}
}else {
echo "0 results";
}
}
?>
Before the mods get the pitchforks, I have to clear up my troubleshooting logic.
Encoding. I set the page encoding to utf-8 using header('Content-Type:
text/html; charset=utf-8'); and ran the queries mysqli_query($conn,"SET NAMES 'utf8'"); and mysqli_query($conn,'SET CHARACTER SET utf8');, this cleared up the ??????? and Ùؤتا
rendered instead of Arabic words issue. That is kind of a different
issue. Source. and Source2.
Database Charset. My database and columns are set to UTF-8.
Other clients work. SQLBuddy/MySQL native client/ PHPMyAdmin appear to be working because running the same exact query yields result. Therefore I appear to be on the same bloody boat with him. The query SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' returns a result on SQLbuddy but nada on PHP.
Possible solution:
Running the query SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' yields me a result.
However running the query with a UTF-8 encoded version of the Arabic word returns 0 results. SELECT * FROM dictionary WHERE ARABIC LIKE 'آخَر، أُخرى' I think this simulates PHP.
The UTF-8 Arabic word version is obtained by decoding the automatically URL encoded $[_GET] parameter i.e %26%231570%3B%26%231582%3B%26%231614%3B%26%231585%3B%26%231548%3B+%26%231571%3B%26%231615%3B%26%231582%3B%26%231585%3B%26%231609%3B
Could it be that the MySQLi actually queries the UTF-8 version instead of the actual Arabic word? Therefore finding no match since they are different?
If so how can I explicitly tell PHP not to URL encode my search term and therefore pass it as it is?
Since according to my tinfoil theory, http://localhost/hans_wehr/search_ar.php?search=آخَر، أُخرى would work but http://localhost/hans_wehr/search_ar.php?search=%26%231570%3B%26%231582%3B%26%231614%3B%26%231585%3B%26%231548%3B+%26%231571%3B%26%231615%3B%26%231582%3B%26%231585%3B%26%231609%3B
Inputs will be greatly appreciated.
Use html_entity_decode():
Use html_entity_decode() on your $_GET["search"] value
<?php
$host = "localhost";
$username = "hans_wehr_client";
// i know my security is a joke :)
$password = "hans_wehr";
$database = "hans_wehr";
$conn = new mysqli($host, $username, $password, $database);
if ($conn == TRUE){
$search = $_GET["search"];
$encoded_search =html_entity_decode($search, ENT_COMPAT, 'UTF-8');
echo $encoded_search."<br>";
header('Content-Type: text/html; charset=utf-8');
$sql = "SELECT * FROM dictionary WHERE ARABIC LIKE '$encoded_search'";
echo $sql."<br>";
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
header('Content-Type: text/html; charset=utf-8');
echo $row["ARABIC"]. " - Meaning: " . $row["ENGLISH1"]. " " . $row["ENGLISH2"]. "<br>";
}
}else {
echo "0 results";
}
}
?>
core.php
$con=mysqli_connect("localhost","root","","mmogezgini");
header('Content-Type: text/html; charset=utf-8');
gamelisti.php
$result = mysqli_query($con,"SELECT * FROM games");
while($row = mysqli_fetch_array($result))
{
?>
HTML CODES
<?php echo $row['game_name']; ?>
HTML CODES
<?php }
mysqli_close($con);
?>
i use turkish characters like "ö,ç,ğ,ı" i see these correctly in database but when i select them from database and show with php echo they looks like question mark=(?)
my encoding on database utf8_general_ci
Double check your HTML encoding.
http://php.net/manual/en/mysqli.set-charset.php (just after you connect to DB: mysqli_set_charset($con, 'utf8');
Are you using prepared statements? (not related but important).
I have a PHP script that gets a XML, selects some data, and insert them in my database (MySQL). All my fields are utf8_bin. This XML is ISO-8859-1, and can't change this because is another site that sends it to me.
Example: the string "NG Contábil" is set "NG Contábil" in my db. This is my script:
<?php
header('Content-Type: text/html; charset=utf-8');
mysql_query("SET NAMES 'utf8'");
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_results=utf8');
include '/PagSeguroLibrary/PagSeguroLibrary.php';
include '/PagSeguroLibrary/domain/PagSeguroAccountCredentials.class.php';
include 'conexao.php';
include 'alias_array.php';
include 'retorna_cpf.php';
$conexao = ConectaBD::get_instance();
$conexao->conectar_pronto();
$conexao->BD_pronto();
//(...)
$xml = simplexml_load_file('arquivo.xml');
if($xml === null)
$xml = simplexml_load_string($resposta_transacao);
$status = $xml->status;
$nome = $xml->sender->name;
$email = $xml->sender->email;
$codigo = $xml->code;
$vetor = $xml->items->item;
$cpf = retorna_cpf($email);
foreach($vetor as $v)
{
$nome_produto = $v->description;
if($nome_produto != 'frete')
{
//Retorna o id do produto a partir da descrição
$result = mysql_query('SELECT id_product
FROM ps_product_lang
WHERE name = "'.$nome_produto.'"');
$array = Array();
while($row = mysql_fetch_alias_array($result))
{
foreach($row as $linha)
array_push($array, $linha);
}
mysql_query('INSERT INTO pagamento(Status, Nome, Email, CPF, idproduto, Codigo, Inscrito, id, Enviado, NomeProduto)
VALUES ("'.$status.'", "'.$nome.'", "'.$email.'", "'.$cpf.'", "'.$array[0].'", "'.$codigo.'", 0, null, 0, "'.$nome_produto.'")');
}
}
fclose($arquivo);
unlink('arquivo.xml');
?>
Thanks for any answer!
You have overlooked just one little nuance:
mysql_query("SET NAMES 'utf8'"); is not a magical spell that have to be cast in order to make proper encoding, but actually an SQL query, which needs to be run in the same instance you are actually using to run SQL queries.
So, if you are connecting to your mysql database using ConectaBD::get_instance(); you have to run SET NAMES utf8 query after that call, not before.
I don't know why, but adding utf8_decode() solves the problem
I know.
simplexml's output is always utf-8.
While, as I pointed out above, you don't set your client connection into utf8.
So, it remains default latin1
With (quite useless) utf8_decode() call you're casting your utf-8 data back into latin1 and thus it correctly stored into database.
This should solve your issue:
...
$xml = simplexml_load_file('arquivo.xml');
$xml = iconv('ISO-8859-1', 'UTF-8', $xml);
...