PHP 基础
PHP 简介
PHP 入门
PHP 语法
PHP 变量
PHP 常量
PHP 输出和打印
PHP 数据类型
PHP 字符串
PHP 运算符
PHP If…Else
PHP Switch…Case
PHP 数组
PHP 数组排序
PHP 循环
PHP 函数
PHP 数学运算
PHP GET 和 POST
PHP 高级
PHP 日期和时间
PHP 包含文件
PHP 文件系统
PHP 解析目录
PHP 文件上传
PHP 文件下载
PHP Cookies
PHP Sessions
PHP 发送邮件
PHP 表单处理
PHP 表单验证
PHP 过滤器
PHP 错误处理
PHP 类和对象
PHP 魔术常量
PHP JSON 解析
PHP 正则表达式
PHP 异常处理
PHP 和 MySQL 数据库
PHP MySQL 简介
PHP MySQL 连接
PHP MySQL Create Database
PHP MySQL Create Table
PHP MySQL Insert
PHP MySQL Prepared
PHP MySQL Last Inserted ID
PHP MySQL Select
PHP MySQL Where
PHP MySQL Limit
PHP MySQL Order By
PHP MySQL Update
PHP MySQL Delete
PHP MySQL CRUD 应用
PHP MySQL Ajax 搜索
PHP MySQL 登录系统
PHP参考
PHP String Functions
PHP Array Functions
PHP File System Functions
PHP Date/Time Functions
PHP Calendar Functions
PHP MySQLi Functions
PHP Filters
PHP Error Levels
PHP常见问题解答
如何在 PHP 中编写注释
如何在 PHP 中删除字符串中的空格
如何在 PHP 中查找字符串中的字符数
如何在 PHP 中查找字符串中的单词数
如何在 PHP 中删除字符串中的特殊字符
如何在 PHP 中替换字符串中的一个单词
如何在 PHP 中对字符串前面追加
如何在 PHP 中对字符串后面追加
如何在 PHP 中从字符串中提取子串
如何在 PHP 中比较两个字符串
如何在 PHP 中获取当前页面的 URL
如何在 PHP 中通过连接数组值创建字符串
如何在 PHP 中将字符串拆分为数组
如何在 PHP 中合并两个字符串
如何在 PHP 中把字符串转换成小写字母
如何在 PHP 中把字符串转换成大写字母
如何在 PHP 中把字符串的第一个字母转换成大写字母
如何在 PHP 中把特殊的 HTML 实体转换回字符
如何在 PHP 中删除字符串开头的空格
如何在 PHP 中删除字符串结尾的空格
如何在 PHP 中新建一行
如何在 PHP 中查找字符串长度
如何在 PHP 中检查变量是否已设置
如何在 PHP 中检查变量是否为空
如何在 PHP 中检查变量是否为NULL
如何在 PHP 中反转字符串
如何在 PHP 中用另一个字符串替换字符串的一部分
如何在 PHP 中计算子串在字符串中出现的次数
如何在 PHP 中计算数组中的所有元素
如何在 PHP 中打印或回显数组的所有值
如何在 PHP 中显示数组的结构和值
如何在 PHP 中颠倒数组的顺序
如何在 PHP 中检查数组中是否存在值
如何在 PHP 中检查数组中是否存在键
如何在 PHP 中删除数组中的最后一个元素
如何从 PHP 数组中删除第一个元素
如何在 PHP 中为数组的开头添加元素
如何在 PHP 中为数组的末尾添加元素
如何在 PHP 中把两个或多个数组合并成一个数组
如何在 PHP 中按字母顺序对数组值排序
如何在 PHP 中删除数组中的重复值
如何在 PHP 中随机调整数组的顺序
如何在 PHP 中比较两个数组的值
如何在 PHP 中计算数组中数值的总和
如何在 PHP 中删除数组中的空值
如何在 PHP 中用数组值填充下拉列表
如何在 PHP 中获取关联数组的所有键值
如何在 PHP 中获取关联数组的所有值
如何在 PHP 中按键对关联数组排序
如何在 PHP 中按值对关联数组排序
如何在 PHP 中从数组中获取单个值
如何在 PHP 中循环浏览多维数组
如何在 PHP 中从数组中删除元素
如何在 PHP 中检查字符串是否包含特定单词
如何在 PHP 中获取当前日期和时间
如何在 PHP 中进行重定向
如何在 PHP 中删除字符串中的所有空格
如何用 PHP 获取当前年份
如何在 PHP 中将日期从 yyyy-mm-dd 转换为 dd-mm-yyyy 格式
如何在 PHP 中将字符串转换为数字
如何在 PHP 中获取数组的第一个元素
如何在 PHP 中将日期转换为时间戳
如何在 PHP 中为空数组添加元素
如何在 PHP 中把整数转换成字符串
如何用值而不是键删除 PHP 数组元素
如何在 PHP 中将键和值同时推入数组
如何使用 PHP 定期刷新页面
如何从 PHP 字符串中删除最后一个字符
如何从 PHP 脚本返回 JSON
如何让 PHP 显示错误
PHP JSON 解析 - php7基础教程 - 笔下光年
网站首页
PHP JSON 解析
n this tutorial you will learn how to encode and decode JSON data in PHP. ## What is JSON JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format which is quick and easy to parse and generate. JSON, like XML, is a text-based format that's easy to write and easy to understand for both humans and computers, but unlike XML, JSON data structures occupy less bandwidth than their XML versions. JSON is based on two basic structures: - **Object**: This is defined as a collection of key/value pairs (i.e. `key:value`). Each object begins with a left curly bracket `{` and ends with a right curly bracket `}`. Multiple key/value pairs are separated by a comma `,`. - **Array**: This is defined as an ordered list of values. An array begins with a left bracket `[` and ends with a right bracket `]`. Values are separated by a comma `,`. In JSON, keys are always strings, while the value can be a **string**, **number**, **true** or **false**, **null** or even an **object** or an **array**. Strings must be enclosed in double quotes `"` and can contain escape characters such as `\n`, `\t` and `\`. A JSON object may look like this: ```json { "book": { "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "genre": "Fantasy Fiction", "bestseller": true } } ``` Whereas an example of JSON array would look something like this: ```json { "fruits": [ "Apple", "Banana", "Strawberry", "Mango" ] } ``` <div class="callout callout-success mb-3">Tip: A data-interchange format is a text format which is used to interchange or exchange data between different platforms and operating systems. JSON is the most popular and lightweight data-interchange format for web applications.</div> ## Parsing JSON with PHP JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are `json_encode()` and `json_decode()`, respectively. Both functions only works with UTF-8 encoded string data. ## Encoding JSON Data in PHP In PHP the `json_encode()` function is used to encode a value to JSON format. The value being encoded can be any [PHP data type](http://www.bixiaguangnian.com/manual/php7/3969.html "PHP data type") except a resource, like a database or file handle. The below example demonstrates how to encode a [PHP associative array](http://www.bixiaguangnian.com/manual/php7/3974.html "PHP associative array") into a JSON object: ```php <?php // An associative array $marks = array("Peter"=>65, "Harry"=>80, "John"=>78, "Clark"=>90); echo json_encode($marks); ?> ``` The output of the above example will look like this: ```json {"Peter":65,"Harry":80,"John":78,"Clark":90} ``` Similarly, you can encode the PHP indexed array into a JSON array, like this: ```php <?php // An indexed array $colors = array("Red", "Green", "Blue", "Orange", "Yellow"); echo json_encode($colors); ?> ``` The output of the above example will look like this: ``` ["Red","Green","Blue","Orange","Yellow"] ``` You can also force `json_encode()` function to return an [PHP indexed array](http://www.bixiaguangnian.com/manual/php7/3974.html "PHP indexed array") as JSON object by using the `JSON_FORCE_OBJECT` option, as shown in the example below: ```php <?php // An indexed array $colors = array("Red", "Green", "Blue", "Orange"); echo json_encode($colors, JSON_FORCE_OBJECT); ?> ``` The output of the above example will look like this: ```json {"0":"Red","1":"Green","2":"Blue","3":"Orange"} ``` As you can see in the above examples a non-associative array can be encoded as array or object. However, an associative array always encoded as object. ## Decoding JSON Data in PHP Decoding JSON data is as simple as encoding it. You can use the PHP json_decode() function to convert the JSON encoded string into appropriate PHP data type. The following example demonstrates how to decode or convert a JSON object to [PHP object](http://www.bixiaguangnian.com/manual/php7/3994.html "PHP object"). ```php <?php // Store JSON data in a PHP variable $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}'; var_dump(json_decode($json)); ?> ``` The output of the above example will look something like this: ``` object(stdClass)#1 (4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) } ``` By default the `json_decode()` function returns an object. However, you can optionally specify a second parameter `$assoc` which accepts a boolean value that when set as `true` JSON objects are decoded into associative arrays. It is `false` by default. Here's an example: `<?php // Store JSON data in a PHP variable $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}'; var_dump(json_decode($json, true)); ?>` The output of the above example will look something like this: ``` array(4) { ["Peter"]=> int(65) ["Harry"]=> int(80) ["John"]=> int(78) ["Clark"]=> int(90) } ``` Now let's check out an example that will show you how to decode the JSON data and access individual elements of the JSON object or array in PHP. ```php <?php // Assign JSON encoded string to a PHP variable $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}'; // Decode JSON data to PHP associative array $arr = json_decode($json, true); // Access values from the associative array echo $arr["Peter"]; // Output: 65 echo $arr["Harry"]; // Output: 80 echo $arr["John"]; // Output: 78 echo $arr["Clark"]; // Output: 90 // Decode JSON data to PHP object $obj = json_decode($json); // Access values from the returned object echo $obj->Peter; // Output: 65 echo $obj->Harry; // Output: 80 echo $obj->John; // Output: 78 echo $obj->Clark; // Output: 90 ?> ``` You can also loop through the decoded data using [foreach()](http://www.bixiaguangnian.com/manual/php7/3976.html#h2-php-foreach-loop "foreach()") loop, like this: ```php <?php // Assign JSON encoded string to a PHP variable $json = '{"Peter":65,"Harry":80,"John":78,"Clark":90}'; // Decode JSON data to PHP associative array $arr = json_decode($json, true); // Loop through the associative array foreach($arr as $key=>$value){ echo $key . "=>" . $value . "<br>"; } echo "<hr>"; // Decode JSON data to PHP object $obj = json_decode($json); // Loop through the object foreach($obj as $key=>$value){ echo $key . "=>" . $value . "<br>"; } ?> ``` ## Extracting Values from Nested JSON Data in PHP JSON objects and arrays can also be nested. A JSON object can arbitrarily contains other JSON objects, arrays, nested arrays, arrays of JSON objects, and so on. The following example will show you how to decode a nested JSON object and print all its values in PHP. ```php <?php // Define recursive function to extract nested values function printValues($arr) { global $count; global $values; // Check input is an array if(!is_array($arr)){ die("ERROR: Input is not an array"); } /* Loop through array, if value is itself an array recursively call the function else add the value found to the output items array, and increment counter by 1 for each value found */ foreach($arr as $key=>$value){ if(is_array($value)){ printValues($value); } else{ $values[] = $value; $count++; } } // Return total count and values found in array return array('total' => $count, 'values' => $values); } // Assign JSON encoded string to a PHP variable $json = '{ "book": { "name": "Harry Potter and the Goblet of Fire", "author": "J. K. Rowling", "year": 2000, "characters": ["Harry Potter", "Hermione Granger", "Ron Weasley"], "genre": "Fantasy Fiction", "price": { "paperback": "$10.40", "hardcover": "$20.32", "kindle": "4.11" } } }'; // Decode JSON data into PHP associative array format $arr = json_decode($json, true); // Call the function and print all the values $result = printValues($arr); echo "<h3>" . $result["total"] . " value(s) found: </h3>"; echo implode("<br>", $result["values"]); echo "<hr>"; // Print a single value echo $arr["book"]["author"] . "<br>"; // Output: J. K. Rowling echo $arr["book"]["characters"][0] . "<br>"; // Output: Harry Potter echo $arr["book"]["price"]["hardcover"]; // Output: $20.32 ?> ```
上一篇:
PHP 魔术常量
下一篇:
PHP 正则表达式