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' => 'rahul@gmail.com');
echo json_encode($arr2);
?>
输出
{"名字": " Rahul","姓氏": " Kumar","电子邮件": " rahul@gmail.com"}

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
?>
输出
数组(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" : "rahul@gmail.com"}';
var_dump(json_decode($json2, true));
?>
输出
array(3) {
  ["firstName"]=> string(5) "Rahul"
  ["lastName"]=> string(5) "Kumar"
  ["email"]=> string(15) "rahul@gmail.com"
}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4