Why Would Json_Encode Return an Empty String

Why would json_encode return an empty string

Well after 2 hours of digging (cf Edits)

I found out following :

  • In my case it's a encoding problem
  • mb_detect_encoding returns probably a faulty response, some strings were probably not UTF-8
  • using utf8_encode() on those string solved my problem, but see note below

Here is a recursive function that can force convert to UTF-8 all the strings contained in an array:

function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}

Use it simply like this:

echo json_encode(utf8ize($data));

Note: utf8_encode() encodes ISO-8859-1 string to UTF-8 as per the docs so if you are unsure of the input encoding iconv() or mb_convert_encoding() may be better options as noted in comments and other solutions.

Why json_encode returns empty brackets?

The array you show has all the properties as private. this mean that this value are not available outside their class's scope.

you can look at this SO for some suggestion

Using json_encode on objects in PHP (regardless of scope)

echo json_encode returns an empty string

Since you are using PDO, you need to set the encoding like so...

$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC;charset=utf8",$username, $password);

When you obtain data from MySQL any text will be encoded in "client encoding", which is likely windows-1252 if you don't configure it otherwise. The character that is causing your problem is the "curly quote", seen as 92 in the hex dump, which confirms that the mysql client is encoding text in windows-1252.

call mysqli_set_charset("utf8") if you use mysqli

add the charset parameter to the connection string if you use PDO and PHP >= 5.3.6. In earlier versions you need to execute SET NAMES utf8.

PHP print_r works, but json_encode returns empty

json_encode only supports UTF-8 encoded strings, so you'll have to encode your order_item_name values using either htmlentities or utf8_encode

foreach($array1 as &$v) {
$v['order_item_name'] = utf8_encode($v['order_item_name']);
}

print json_encode($array1);

For more info see problems with german umlauts in php json_encode

PHP json_encode returning empty sctructure

You have protected and private attributes, so you can not use any functions, including json_encode() to access directly to your object's property.

Use JSONSerialize

Why does Json_encode return an empty array?

There is an error in the syntax of your json near to "Product_Name".

The values ​​must be strings and therefore between "".

Tell us if you have resolution problems :)

Have a good day !

getting an empty string with json_encode()

json_encode does not serialize private (or protected) member variables. Either copy your object's state into a temporary array or declare member variables as public to mitigate that.



Related Topics



Leave a reply



Submit