如何在不使用json_encode()的情况下将数组编码为JSON? [英] How do I encode an array to JSON without json_encode()?

查看:148
本文介绍了如何在不使用json_encode()的情况下将数组编码为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PHP非常陌生,但是现在我必须帮助我的朋友解决PHP问题.

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

他已经购买了一个基于PHP的网站,将其上传到主机后,发现错误:

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

代码很简单:

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

它将json发送到客户端.

It send a json to client.

我知道json_encode是在php 5.2之后添加的,但是他的主机的PHP版本是PHP 5.1.2,所以这就是它报告错误的原因.

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.

但是我们无权升级主机的PHP版本,因此我必须修改代码.

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?

客户端浏览器中的网页将运行以下javascript代码,以获取并检查json:

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
        }
    }
}

非常感谢!

更新

由于我无权升级任何东西或在该主机上安装新的库,所以我唯一能做的就是更改代码.但是我几乎对php一无所知,我也不知道如何使用3rd party库.最后,我将其修复为:

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:

在php中:

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

在javascript中

In javascript:

if(json!=null && json.result=="true") {
    // do something
}

推荐答案

首先:您应该强烈考虑升级,因为不再支持PHP 5.1.x和5.2.x.您表示您无权这样做,但是如果您是付费客户,那应该有所帮助.从最新的PHP 5.3.6版本开始,不再推荐使用PHP 5.2. a>.

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.

PHP.net上的用户提供了自定义函数一样. 您可以将其重命名为json_decode()并将其包装在if (!function_exists('json_encode'))语句中:

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
     }
}

这篇关于如何在不使用json_encode()的情况下将数组编码为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆