PHP基础之解析json数据

时间:2021-10-13 07:37:07

个人认为,不论是java还是php,解析json都比解析xml简单方便,下面记录使用php解析json数据的例子:

先来一个简单的,json数据只包含普通的键值对,没有数组的情况,下面是json.txt文件的内容:

{
"name" : "zhangsan",
"age" : 21,
"sex" : "male"
}
解析的php代码如下:

<?php
$content = file_get_contents("json2.txt");
$jsonObj = json_decode($content);
$name = $jsonObj->name;
$age = $jsonObj->age;
$sex = $jsonObj->sex;
echo "name = $name<br>";
echo "age = $age<br>";
echo "sex = $sex<br>";
?>
主要是用json_decode()函数,将json字符串解析成json对象,然后根据键取出值,在浏览器中输出为:

PHP基础之解析json数据
下面看json数据中带有数组的情况,json数据为:

{
"name": "zhangsan",
"age": 21,
"sex": "male",
"books": [
{
"name": "Chinese",
"price": "50"
},
{
"name": "History",
"price": "60"
},
{
"name": "Music",
"price": "30"
}
]
}
解析的php代码也不复杂:

<?php
$content = file_get_contents("json2.txt");
$jsonObj = json_decode($content);
$name = $jsonObj->name;
$age = $jsonObj->age;
$sex = $jsonObj->sex;
echo "name = $name<br>";
echo "age = $age<br>";
echo "sex = $sex<br>";
$arr = $jsonObj->books;
$count = count($arr);
for($i = 0; $i < $count; $i++){
$obj = $arr[$i];
$bookName = $obj->name;
$bookPrice = $obj->price;
echo "book name = $bookName, book price = $bookPrice<br>";
}
?>
在浏览器中的输出为:

PHP基础之解析json数据
跟之前解析xml比起来,感觉还是json数据容易解析得多。。。