PHP json示例
PHP JSON PHP允许我们借助json_encode()和json_decode函数对JSON进行编码和…
PHP JSON
PHP允许我们借助json_encode()和json_decode函数对JSON进行编码和解码。
1)PHP json_encode
json_encode()函数返回值的JSON表示形式。换句话说,它将PHP变量(包含数组)转换为JSON。
句法:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
PHP json_encode示例1
让我们看一下编码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_encode示例2
让我们看一下编码JSON的示例。
<?php
$arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => '[email protected]');
echo json_encode($arr2);
?>
输出量
{"firstName":"Rahul","lastName":"Kumar","email":"[email protected]"}
2)PHP json_decode
json_decode()函数解码JSON字符串。换句话说,它将JSON字符串转换为PHP变量。
句法:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
PHP json_decode示例1
让我们看一下解码JSON字符串的示例。
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));//true means returned object will be converted into associative array
?>
输出量
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
PHP json_decode示例2
让我们看一下解码JSON字符串的示例。
<?php
$json2 = '{"firstName" : "Rahul", "lastName" : "Kumar", "email" : "[email protected]"}';
var_dump(json_decode($json2, true));
?>
输出量
array(3) {
["firstName"]=> string(5) "Rahul"
["lastName"]=> string(5) "Kumar"
["email"]=> string(15) "[email protected]"
}
类别:PHP 技巧、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

还没有任何评论,赶紧来占个楼吧!