Sometime recently my WordPress plugin started failing in my DEV environment (on two different boxes) on an AJAX call. What I see is that when I call:
$t = json_encode(<some array>);
an extraneous + character is inserted into the output buffer. I observed this by viewing the result of an ob_get_content() call. $t shows the correct JSON results, and the contents of <some array> doesn’t seem to matter.
I determined it’s not a PHP issue in and of itself, as it only seems to occur within the context of WordPress.
I isolated it to the following function in my plugin:
function my_action_callback() {
$a = array("a" => "orange", "b" => "banana", "c" => "apple");
echo json_encode($a);
die(); // this is required to return a proper result
}
my_action_callback is a callback function registered to be called by WordPress on an AJAX call. I can assign the results of json_encode to a variable instead of echoing, and the results are fine, but checking the output buffer at that point shows a single + already inserted.
Unfortunately, I am not sure what change I made in my environment started this behavior, since I waited too long to debug this. I’m not sure where to start now.
The environment is PHP 5.3.5 running WordPress 3.2.1
Why would calling json_encode put ANYTHING in the output buffer, since I am not echoing the results?
Start with a clean PHP env, write and see if it prints the +. If it does, it’s a PHP bug.
Get rid of the code above, put in your code and see if it prints the +. If it does, it’s a bug in your code.
Start re-doing you modifications to the PHP env. Test, after each change, it it prints the +. When it does, you’ve found the culprit.
If, at the end, you still can’t see the +, then it’s magic. 😉
Take home lesson: never let bugs linger around for too long.