当前位置: 首页 > 编程文章 >

PHP中JSON处理详解:编码、解码及兼容性问题

PHP中JSON处理详解:编码、解码及兼容性问题

作者:陈川时间:2025-05-26 11:56:09浏览:542

JSON已成为主流的数据交换格式,PHP自5.2版本起原生支持json_encode()和json_decode()函数。本文详细解析这两个函数的行为差异,包括索引数组与关联数组的转换规则、类实例的属性过滤机制,以及解码时强制返回数组的参数设置。同时指出JSON语法中的常见错误,如引号使用和尾随逗号问题。针对低版本PHP缺乏内置支持的兼容性需求,文中还提供了基于json2.js标准的手动实现方案。

本文目录展开

PHP中JSON处理详解:编码、解码及兼容性问题

如今,JSON已演变为最广泛采用的数据交换格式,绝大多数网站的API接口均对其提供支持。

此前曾撰文探讨过其设计哲学,此处重点梳理PHP语言对JSON的支持机制,这是构建互联网应用尤其是开发API时的必备技能。

自5.2版本起,PHP原生内置了json_encode()用于编码以及json_decode()用于解码两个核心函数。

一、json_encode()函数详解

该函数主要用于将PHP数组或对象转换为JSON格式字符串。首先观察一个数组转换的具体示例:


$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

执行后的输出结果为:

{"a":1,"b":2,"c":3,"d":4,"e":5}

接着查看一个对象转换的示例:


$obj->body      = 'another post';
$obj->id       = 21;
$obj->approved    = true;
$obj->favorite_count = 1;
$obj->status     = NULL;
echo json_encode($obj);

对应的输出结果为:


{
    "body":"another post", 
    "id":21,
    "approved":true,
    "favorite_count":1,
    "status":null
}

鉴于JSON规范仅接受UTF-8编码字符,json_encode()的输入参数必须为UTF-8编码,否则可能返回空字符串或null。当处理GB2312编码的中文或ISO-8859-1编码的外文时,务必注意此编码限制。

二、索引数组与关联数组的区别

PHP包含两种数组类型:仅保存值(value)的索引数组(indexed array),以及保存名值对(name/value)的关联数组(associative array)。

因JavaScript不支持关联数组概念,json_encode()会将索引数组转换为JSON数组格式,而将关联数组转换为JSON对象格式。

例如,定义如下索引数组:


$arr = Array('one', 'two', 'three');
echo json_encode($arr);

转换结果为:

["one","two","three"]

若将其修改为关联数组:


$arr = Array('1'=>'one', '2'=>'two', '3'=>'three');
echo json_encode($arr);

结果结构发生变化:


{"1":"one","2":"two","3":"three"}

需注意,数据格式已从方括号“[]”(数组)变为花括号“{}”(对象)。

若需强制将索引数组转换为对象,可采用以下写法:


json_encode( (object)$arr );

或者使用常量选项:


json_encode ( $arr, JSON_FORCE_OBJECT );

三、类(class)对象的转换规则

考虑以下PHP类定义:


class Foo {
    const   ERROR_CODE = '404';
    public  $public_ex = 'this is public';
    private  $private_ex = 'this is private!';
    protected $protected_ex = 'this should be protected';
    public function getErrorCode() {
      return self::ERROR_CODE;
    }
}

对该类的实例进行JSON转换操作:


$foo = new Foo;
$foo_json = json_encode($foo);
echo $foo_json;

最终输出结果为:

{"public_ex":"this is public"}

由此可见,除了公开变量(public)外,其他成员如常量、私有变量及方法等均会被丢弃。

四、json_decode()函数解析

该函数负责将JSON文本还原为相应的PHP数据结构。示例如下:


$json = '{"foo": 12345}';  
$obj = json_decode($json); 
print $obj->{'foo'}; // 12345

默认情况下,json_decode()返回的是PHP对象而非数组。例如:


$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';  
var_dump(json_decode($json));

生成的结果是一个PHP对象:


object(stdClass)#1 (5) {
  
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
  
}

若希望强制生成PHP关联数组,需向json_decode()传入第二个参数true:


$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json,true));

此时结果变为关联数组:


array(5) {
  
     ["a"] => int(1)
     ["b"] => int(2)
     ["c"] => int(3)
     ["d"] => int(4)
     ["e"] => int(5)
  
} 

五、json_decode()常见错误排查

以下三种JSON写法均为非法,请识别其中的错误:


$bad_json = "{ 'bar': 'baz' }";
$bad_json = '{ bar: "baz" }';  
$bad_json = '{ "bar": "baz", }';

对上述字符串执行json_decode()均会返回null并触发报错。

第一个错误在于JSON分隔符仅限双引号,不可使用单引号;第二个错误是键名(冒号左侧部分)在任何情况下都必须使用双引号包裹;第三个错误是最后一个值后严禁添加逗号(trailing comma)。

此外,JSON仅适用于表示对象和数组,若对普通字符串或数值调用json_decode(),将直接返回null。


var_dump(json_decode("Hello World")); //null

接下来介绍PHP语言的JSON底层实现方案

在开发ajax file manager for web开源项目时,由于数据交互采用JSON格式,发现在低版本PHP环境中运行异常。经调试确认,原因是低版本PHP未实现json_decode和json_encode函数。为确保兼容性,自行编写了一套PHP版JSON编解码代码,并与json2.js保持行为一致,经测试验证无误,现公布供有相同需求的开发者参考:


<?php 
/* * **************************************************************************** 
 * $base: $ 
 * 
 * $Author: $ 
 *   Berlin Qin 
 * 
 * $History: base.js $ 
 *   Berlin Qin  //     created 
 * 
 * $contacted 
 *   webfmt@gmail.com 
 *   www.webfmt.com 
 * 
 * *************************************************************************** */ 
/* =========================================================================== 
 * license 
 * 
 * 、Open Source Licenses 
 * webfmt is distributed under the GPL, LGPL and MPL open source licenses. 
 * This triple copyleft licensing model avoids incompatibility with other open source licenses. 
 * These Open Source licenses are specially indicated for: 
 *  Integrating webfmt into Open Source software; 
 *  Personal and educational use of webfmt; 
 *  Integrating webfmt in commercial software, 
 * taking care of satisfying the Open Source licenses terms, 
 *  while not able or interested on supporting webfmt and its development. 
 * 
 * 、Commercial License – fbis source Closed Distribution License - CDL 
 * For many companies and products, Open Source licenses are not an option. 
 * This is why the fbis source Closed Distribution License (CDL) has been introduced. 
 * It is a non-copyleft license which gives companies complete freedom 
 * when integrating webfmt into their products and web sites. 
 * This license offers a very flexible way to integrate webfmt in your commercial application. 
 * These are the main advantages it offers over an Open Source license: 
 *   Modifications and enhancements doesn't need to be released under an Open Source license; 
 *   There is no need to distribute any Open Source license terms alongside with your product 
 * and no reference to it have to be done; 
 *   No references to webfmt have to be done in any file distributed with your product; 
 *   The source code of webfmt doesn't have to be distributed alongside with your product; 
 *   You can remove any file from webfmt when integrating it with your product. 
 * The CDL is a lifetime license valid for all releases of webfmt published during 
 * and before the year following its purchase. 
 * It's valid for webfmt releases also. It includes year of personal e-mail support. 
 * 
 * ************************************************************************************************************************************************* */ 
function jsonDecode($json) 
{ 
  $result = array(); 
  try 
  { 
    if (PHP_VERSION_ID > ) 
    { 
      $result = (array) json_decode($json); 
    } 
    else 
    { 
      $json = str_replace(array("\\\\", "\\\""), array("&#;", "&#;"), $json); 
      $parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
      foreach ($parts as $index => $part) 
      { 
        if (strlen($part) == ) 
        { 
          switch ($part) 
          { 
            case "[": 
            case "{": 
              $parts[$index] = "array("; 
              break; 
            case "]": 
            case "}": 
              $parts[$index] = ")"; 
              break; 
            case ":": 
              $parts[$index] = "=>"; 
              break; 
            case ",": 
              break; 
            default: 
              break; 
          } 
        } 
      } 
      $json = str_replace(array("&#;", "&#;", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts)); 
      $result = eval("return $json;"); 
    } 
  } 
  catch (Exception $e) 
  { 
    $result = array("error" => $e->getCode()); 
  } 
  return $result; 
} 
function valueTostr($val) 
{ 
  if (is_string($val))  
  { 
    $val = str_replace('\"', "\\\"", $val); 
    $val = str_replace("\\", "\\\\", $val); 
    $val = str_replace("/", "\\/", $val); 
    $val = str_replace("\t", "\\t", $val); 
    $val = str_replace("\n", "\\n", $val); 
    $val = str_replace("\r", "\\r", $val); 
    $val = str_replace("\b", "\\b", $val); 
    $val = str_replace("\f", "\\f", $val); 
    return '"' . $val . '"'; 
  } 
  elseif (is_int($val)) 
    return sprintf('%d', $val); 
  elseif (is_float($val)) 
    return sprintf('%F', $val); 
  elseif (is_bool($val)) 
    return ($val ? 'true' : 'false'); 
  else 
    return 'null'; 
} 
function jsonEncode($arr) 
{ 
  $result = "{}"; 
  try 
  { 
    if (PHP_VERSION_ID > ) 
    { 
      $result = json_encode($arr); 
    } 
    else 
    { 
      $parts = array(); 
      $is_list = false; 
      if (!is_array($arr)) 
      { 
        $arr = (array) $arr; 
      } 
      $end = count($arr) - ; 
      if (count($arr) > ) 
      { 
        if (is_numeric(key($arr))) 
        { 
          $result = "[";  
          for ($i = ; $i < count($arr); $i++) 
          { 
            if (is_array($arr[$i])) 
            { 
              $result = $result . jsonEncode($arr[$i]); 
            } 
            else 
            { 
              $result = $result . valueTostr($arr[$i]); 
            } 
            if ($i != $end) 
            { 
              $result = $result . ","; 
            } 
          } 
          $result = $result . "]"; 
        } 
        else 
        { 
          $result = "{";  
          $i = ; 
          foreach ($arr as $key => $value) 
          { 
            $result = $result . '"' . $key . '":'; 
            if (is_array($value)) 
            { 
              $result = $result . jsonEncode($value); 
            } 
            else 
            { 
              $result = $result . valueTostr($value); 
            } 
            if ($i != $end) 
            { 
              $result = $result . ","; 
            } 
            $i++; 
          } 
          $result = $result . "}"; 
        } 
      } 
      else 
      { 
        $result = "[]"; 
      } 
    } 
  } 
  catch (Exception $e) 
  { 
  } 
  return $result; 
} 
?>

使用过程中如遇任何问题,欢迎发送邮件联系。亦恳请指出代码中的不足之处!

上一篇
PHP流程控制与循环语句详解及替代语法

PHP提供if、elseif、switch等流程控制语句处理条件分支,以及while、for、do...while等循环语句处理重复任务。当条件较多时,switch语句比冗长的elseif更清晰。此外,PHP支持使用冒号和endif/endwhile等关键字的替代语法来替代大括号,简化复杂代码结构。

下一篇
Ubuntu/Debian下PHP Session Permission denied Notice的成因与解决

在Ubuntu或Debian系统中使用apt安装的PHP时,启动Session可能会触发“opendir(/var/lib/php5) failed: Permission denied”的Notice。该问题源于file_handler模式下session_start触发的垃圾回收(GC)尝试以非root身份读取权限为733的目录。通过设置session.gc_probability为0可彻底关闭此检查,或利用系统cron任务处理清理工作。

相关文章

更多
PHP数组转JSON与Java JSON数据格式转换示例

本文介绍PHP中将数组转换为JSON字符串的方法,以及Java环境下使用json-lib库进行JSON对象构建与解析的完整流程。包含必要的依赖包列表、代码实现细节及运行结果展示,并提供实用的在线JSON工具推荐。

2026.02.19 957
PHP构造JSON多维数组的方法示例

本文介绍利用PHP将数据库查询结果序列化为JSON格式的多维数组方法。通过遍历mysqli结果集并填充关联数组,最终使用json_encode函数输出结构化数据。文中还附带了常用的JSON在线校验与美化工具链接。

2026.02.08 866
PHP封装响应类实现JSON与XML数据格式返回

本文介绍如何在PHP中封装一个统一的响应类,以支持JSON和XML两种主流数据格式的返回。该类通过静态方法处理状态码、提示信息及业务数据,针对XML格式特别处理了数字键名导致的标签报错问题,并提供了一个综合接口方便前端或移动端调用。

2025.09.06 852
PHP JSON 函数 json_encode 与 json_decode 用法详解

本文详细介绍 PHP 中处理 JSON 数据的核心函数 json_encode 和 json_decode。通过数组编码为 JSON 字符串以及解码 JSON 字符串为 PHP 对象或数组的实例,展示具体用法与输出结果,并附带实用的在线 JSON 工具链接,帮助开发者快速掌握 JSON 数据处理技巧。

2026.07.30 803
PHP实现JSON处理类及版本要求说明

本文介绍了一个基于PHP语言实现的JSON处理类实例,旨在为开发者提供实用的参考代码。在使用相关功能时需注意环境依赖,其中核心的json_encode函数仅在PHP 5.2.0及以上版本(且PECL json扩展版本大于等于1.2.0)中可用。该资源适合需要处理JSON数据格式的PHP开发人员查阅。

2025.12.01 794
PHP后端与Android客户端JSON数据交互实现

本文展示了PHP服务器端与Android客户端之间通过HTTP协议进行JSON数据交互的完整流程。PHP端接收GET参数并调用模型生成SQL,最终将结果编码为JSON对象返回;Android端在子线程中构建URL参数发起网络请求,解析响应并根据成功或失败状态更新UI或提示错误信息。

2025.10.28 781

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
JSON 结构差异对比
JSON 结构差异对比

比较两份 JSON 的结构与值,忽略对象键顺序,按数组下标定位变更,并生成可复制的 JSON Patch。

键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。