在 php 中使用 json_encode() 内置函数(php > 5.2)是将php中数据类型转换为json数据存储格式,使得 php 中数据可以与其它语言很好的传递并且使用它。

语法:

json_encode(value,option) 

参数:

value:必填。待编码的 value ,除了resource 类型之外,可以为任何数据类型。该函数只能接受 UTF-8 编码的数据

option:可选

option参数详解参考http://www.ecjson.com/article/21.html

      例子1:

<?php
$arr = array
       (
          'name'=>'ecjson',
          'url' =>'www.ecjosn.com'
       );
$jsonencode = json_encode($arr);
echo $jsonencode;
?>

程序运行结果:

{"name":"ecjson","url":"www.ecjson.com"}

例子2:

对象进行json编码

<?php
class mobile{
    public $brand;
    public $color;
    public $weight;
     
    function __construct($brand,$color,$weight){
        $this->brand = $brand;
        $this->color = $color;
        $this->weight = $weight;
    }
}
 
$newMobile = new mobile('mobile',"red","10");
echo json_encode($newMobile);
?>

程序运行结果:

{"brand":"mobile","color":"red","weight":"10"}

PHP json_decode接受一个 JSON 编码的字符串并且把它转换为 PHP 变量,与json_encode相对应。