Undefined json_encode function?
For some strange reason one of my php scripts at work stopped functioning and was throwing a fatal error complaining that the json_encode() function was undefined. I thought this was a bit strange since I could of sworn the previous week it was working fine. I am using the json_encode() function to allow javascript to properly parse data that it requests via AJAX. It allows the parsing of database information in a more efficient manner than other methods I have seen.
It seems that the version of PHP previous to 5.2 do not have the json_encode() function available and this can be a bit of a pain when working with ajax scripts that request information from a MySQL database. I hopefully have found a quick solution by recreating the proper output for those who are running PHP versions 5.1 and older.
$qry = mysql_query("SELECT * FROM blah");
$results = mysql_fetch_array($qry);$json = “{”;
foreach ($results as $field => $value) {
$json = $json . ‘”‘ . $field .’”:”‘. $value .’”,’;
}
$json = substr($json, 0, strlen($json)-1);
$json = $json . ‘}’;echo $json;
What this does is it will go through your previous MySQL query results and insert the field name along with its value into a string which can then be outputted in the proper format for JavaScript to properly parse the data.
This seems to be the quickest way to recreate a json_encode output when it is not available to those who are using PHP version less than 5.2. I have seen various PHP classes on the internet that are bloated and do far more than they really should when you’re just trying to create the function. One PHP class I saw had 50 lines of code! My above example to recreate the function is 6 lines of code (doesn’t include the MySQL lines). Another PHP class I found was broken in various spots and was said to be ‘complete’ and ‘functional’. Oh well, I hope my example helps people out there who need to fix scripts to work with older versions.






April 25th, 2008 at 10:00:50
Other JSON outputting classes/functions are probably able to output JSON for generic types. Your example gets the job done for the most part (assuming you’re always working with a mysql resource) but if you’re working with objects and you want to return an object as a JSON response, more functionality would be required to inspect the members of your object to come up with the proper JSON.
This is something that the json_encode method in PHP 5.2 can do.
April 25th, 2008 at 11:04:41
Kenny - Thanks for explaining it a little better. I’m fairly new to the whole ajax idea and any information I can get my hands on the better.