Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I encode an array to JSON without json_encode()?

Tags:

json

php

I'm very very new to PHP, but now I have to help my friend to solve a PHP problem.

He has bought a web site based on PHP, after he upload it to the host, found there is a error:

Fatal error:  Call to undefined function json_encode() in xxx.php

The code is very simple:

echo json_encode(array(
    'result' => true,
));

It send a json to client.

I know json_encode is added after php 5.2, but the PHP version of his host is PHP 5.1.2, so that's the reason why it reports error.

But we don't have the right to upgrade the PHP version of host, so I have to modify the code. How to let it return a json to client without json_encode?

The webpage in client browser will run this javascript code, to get and check that json:

jQuery.ajax({ 'url': '...', ...,
    'success':function(json) {
        if(json != null && json.result == true) {
           // do something
        }
    }
}

Thanks a lot!


UPDATE

Since I have no rights to upgrade anything or install new libraries to that host, the only thing I can do is change the code. But I nearly know nothing about php, that I don't know how to use 3rd party libraries either. At last, I fix it as this:

In php:

echo '{"result":"true"}';

In javascript:

if(json!=null && json.result=="true") {
    // do something
}
like image 530
Freewind Avatar asked Dec 22 '22 16:12

Freewind


1 Answers

First of all: you should strongly consider upgrading, since PHP 5.1.x and 5.2.x are no longer supported. You indicated that you do not have the rights to do so, but if you are a paying customer, that should count for something. PHP 5.2 is deprecated as of the last PHP 5.3.6 release.

A user on PHP.net has provided for a custom function that does the same. You could rename it to json_decode() and wrap it in a if (!function_exists('json_encode')) statement:

if (!function_exists('json_encode')) {
     function json_encode() {
         // do stuff
     }
}
like image 113
Aron Rotteveel Avatar answered Jan 04 '23 07:01

Aron Rotteveel