PHP 5.2.0,JSON扩展捆绑和编译成PHP 也是默认的支持的。
函数 | 程序库 |
|---|---|
json_encode | 返回JSON表示的值 |
json_decode | 解码为一个JSON字符串 |
json_last_error | 返回上次发生错误 |
PHP json_encode()函数用于在PHP JSON编码。这个函数成功返回JSON表示的值,失败则返回FALSE。
string json_encode ( $value [, $options = 0 ] )下面的例子演示了如何用PHP数组转换成JSON:
<?php
$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}下面的示例显示如何将PHP对象可以转换成JSON:
<?php
class Emp {
public $name = "";
public $hobbies = "";
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"}PHP json_decode()函数用于解码JSON在PHP。这个函数返回值从json解码成适当的 PHP类型。
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])下面的示例显示了如何可以使用PHP来解码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)
}