1

I wrote a PHP class to process a CSV file and upload entries. The last round was over 15,000+ row in the file.

Previously, in my wrapper I would return the json response like so:

echo json_encode($jsonResponse);
wp_die();

That worked fine when we were uploading files that had up to 2,000 rows. Recently, we uploaded a file that had 4,000+ rows and the json response never would print - response would be NULL. After many hours of checking if the file itself was causing the issue, I elected to use the following

wp_send_json($jsonResponse);

And my response would show to the screen as expected. I've looked into the wp_send_json() method and understand it is the expected usage for WP. My question is why did my previous implementation work up to now? I'm assuming the response being ran through manual json_encode() was too large?

I'm looking for insight into the root of the problem here, and a deeper understanding of why my solution is working.

Zach Smith
  • 5,490
  • 26
  • 84
  • 139

1 Answers1

1

I make an assumption that in your case json_encode() returns boolean false. json_encode() never returns null, it returns either a string or false on error. It can, of course, return a string "null", but never "NULL".

Most likely your data contains some binary data (e.g. broken UTF-8), which a valid JSON must not contain. You can check the actual error message by calling json_last_error_msg() after json_encode().

wp_send_json() performs some sanitization against your data, making it json-encodable. But even though it does produce some nice JSON output, the data is effectively "broken" (whether noticeably or not) because the sanitization process modifies the data.

5lava
  • 1,168
  • 11
  • 12