Codementor Events

How I fixed PHP json_encode() returning empty result

Published Nov 15, 2022

If you are building a RESTful API in PHP, then you are most likely using the json_encode function. json_encode is a PHP function that converts an array to JSON format.

In this article, I will discuss how you can fix a json_encode function that returns an empty result or throws an error.

Debugging the error

The first step in solving a problem is to first know what the problem really is.

First, let’s see if there is any error from json_encode. Add the below code in your code after the json_encode() function that you have:

echo json_last_error_msg(); // Print out the error if any
die(); // halt the script

If what was printed out is — “No errors”, then there is nothing wrong with the data.

Here is the list of errors you might encounter:

https://secure.php.net/manual/en/function.json-last-error.php#refsect1-function.json-last-error-examples

Fixing “Malformed UTF-8 characters, possibly incorrectly encoded” error

This is one of the common error you will face especially if you are fetching your data from a database.

I encountered this error personally which prompted me to write this article. I was working with a result which I fetched from the database that I converted to JSON. Below is my complete code:

$courses = [];
 $db = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
 if ($db->connect_error) {
     echo (json_encode([
           'status' => 'error',
           'message' => 'connection to database failed.'
     ]));
     die();
 }
 
 if (isset($_GET['count'])) {
      $allCoursesQuery = "SELECT * FROM `courses`";
      $result = $db->query($allCoursesQuery);
      
      echo json_encode(['count' => $result->num_rows]);
      die();
 }
$allCoursesQuery = "SELECT id, title FROM `courses`";
$result = $db->query($allCoursesQuery);
 
 if ($result->num_rows > 0) {
  while ($row = $result->fetch_assoc()) {
   $courses[] = [
                'id' => $row['id'],
                'title' => $row['title']
   ];
  }
 }
 
echo( json_encode([
   'status' => 'success',
   'data' => $courses
]) );
die();

In the code above, I’m fetching all the courses that are in the courses table that is about 164 records. In the last part of the code, I encode the array of courses to JSON then print out the result.

The result was empty, nothing was printed out. But if I LIMIT the result to like 100 records, I get the JSON printed out but any record I fetch above 100 shows empty.

At first, I thought it might be a memory issue (but 164 records is not that much 😕). I went ahead to increase my memory limit but that did not help. It was not memory related.

After much trial and error, I decided to see what json_encode is complaining about if any. So I placed the code after the json_encode(…) function:

echo json_last_error_msg(); // Print out the error if any
die(); // halt the script

Now, I see the error!:

Malformed UTF-8 characters, possibly incorrectly encoded

This error happens if the result contains mixed encoding characters.

To fix it, I introduced JSON_UNESCAPED_UNICODE:

echo( json_encode([
   'status' => 'success',
   'data' => $courses
], JSON_UNESCAPED_UNICODE) );

Conclusion

In this article, you have learned how to debug common json_encode() error and how to get them fixed. Although we did not discuss how to fix all of the errors independently, I strongly believe you can take it from there as you have known what the error message.

Discover and read more posts from Onwuka Gideon
get started
post commentsBe the first to share your opinion
Show more replies