public $birthdate = "";
   }
   $e = new Emp();
   $e->name = "sachin";
   $e->hobbies  = "sports";
   $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
   $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

   echo json_encode($e);
?>

以上代码执行结果为:

{"name":"sachin","hobbies":"sports","birthdate":"08/05/1974 12:20:03 pm"}

使用 JSON_UNESCAPED_UNICODE 选项

<?php
   $arr = array('runoob' => '菜鸟教程''taobao' => '淘宝网');
   echo json_encode($arr)// 编码中文
   echo PHP_EOL;  // 换行符
   echo json_encode($arr, JSON_UNESCAPED_UNICODE);  // 不编码中文
?>

以上代码执行结果为:

{"runoob":"u83dcu9e1fu6559u7a0b","taobao":"u6dd8u5b9du7f51"}{"runoob":"菜鸟教程","taobao":"淘宝网"}

json_decode

PHP json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量。

语法

mixed json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

参数

  • json_string: 待解码的 JSON 字符串,必须是 UTF-8 编码数据

  • assoc: 当该参数为 TRUE 时,将返回数组,FALSE 时返回对象。

  • depth: 整数类型的参数,它指定递归深度

  • options: 二进制掩码,目前只支持 JSON_BIGINT_AS_STRING 。

实例

以下实例演示了如何解码 JSON 数据:

实例

<?php
   $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

   var_dump(json_decode($json));
   var_dump(json_decode($json, true));
?>

以上代码执行结果为:

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