AndroidNewBee
AndroidNewBee

Reputation: 744

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.

Upvotes: 0

Views: 628

Answers (2)

Rick James
Rick James

Reputation: 142528

$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.

Upvotes: 0

Noman
Noman

Reputation: 1487

Simply add this:

mysqli_set_charset($con, "utf8");

after mysql connect.

Upvotes: 1

Related Questions