Categories
Uncategorized

Empty json_encode() output in php 7.1.x

If you have an empty json_encode() and don’t know what the hell just went wrong, then this piece of code is really helpful.

$json = json_encode(array('message' => 'OK', 'data' => $row["description"]));
if ($json) {
    echo $json;
} else {
    error_log(json_last_error_msg());
}

If you get an error saying invalid UTF-8 characters or something similar, then all you need to do is set the character set of your database to UTF-8 in the following way.

connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    die();
}

 var_dump($mysqli->get_charset());
// you should see something like 'latin1'

 if (!$mysqli->set_charset("utf8")) {
    error_log("Error loading character set utf8: %s\n", $mysqli->error);
    exit();
}

var_dump($mysqli->get_charset());
// you should see something like 'UTF-8'

// Do your stuff here.

$mysqli->close();