rjbogz
rjbogz

Reputation: 870

json_encode echo coming back blank. Possible utf 8 issue?

I am not sure how I can debug this. I get an array from a database, which is returned fine, but when I try to use json_encode on it, it returns blank. Any help is appreciated.

<?php
header('Content-Type: text/html; charset=utf-8');
$servername = "localhost";
$username = "username";
$password = "password";
mysql_connect($servername, $username, $password) or die(mysql_error());
mysql_select_db("places") or die(mysql_error());
$result = mysql_query("SELECT Location, Latitude, Longitude FROM places WHERE Latitude IS NOT NULL GROUP BY Location, Latitude, Longitude");
$places = array();
while (($row = mysql_fetch_array($result, MYSQL_NUM)) !== false) {
    $places[] = $row;
}
$json = json_encode($places, JSON_UNESCAPED_UNICODE);
echo $json;
?>

A sample of what is returned in places[] is:

Array
(
[0] => Array
    (
        [0] => testPlace1
        [1] => 50.1019
        [2] => -75.0263
    )

[1] => Array
    (
        [0] => testPlace2
        [1] => 130.4834
        [2] => 48.3428
    )

[2] => Array
    (
        [0] => testPlace3
        [1] => 23.3003
        [2] => -48.3201
    )
...
....

And that goes on. There are some that have unicode characters in them and that was my initial though, so I added a few things to the php code to help, but I am not sure if it is correct.

Upvotes: 0

Views: 360

Answers (3)

Hedeshy
Hedeshy

Reputation: 1386

The problem is that you used json_encode twice. You can't json_encode what is already a json string.

Also bear in mind that those mysql functions are deprecated. I suggest you to use PDO.

UPDATE

Apparently you have some special alphabets in Location. You can encode them to utf8 this way:

$places = array_map(function($place) {
    $place[0] = utf8_encode($place[0]);
    return $place;
}, $places );

As for JSON_UNESCAPED_UNICODE, after you decode the json the unicode escapes will be mapped to the appropriate UTF-8 strings. Therefore, you don't usually need it.

Upvotes: 2

Pawan
Pawan

Reputation: 3

Your Code Is Right One. Just I have checked it. and i got json output in this format at http://jsonlint.com/ in above format and it it is valid one.

[[\"Test1\",\"50.1019\",\"-75.0263\"],[\"testPlace2\",\"130.4834\",\"48.3428\"]]

Same like this you just run your code and check your json output at : http://jsonlint.com/ it might help you.

Upvotes: 0

avinash hiremath
avinash hiremath

Reputation: 33

In case of utf8 issue, you can use charset for database connection

$connection = mysqli_connect($servername, $username, $password);
mysqli_set_charset($connection,'utf8');

Upvotes: 1

Related Questions