JSON全称“JavaScript Object Notation”,它是一种轻量级的数据交换格式,它给网络传输带来了很大的便利,但是没有XML一目了然。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯,这些特性使JSON成为理想的数据交换语言,易于人阅读和编写,同时也易于机器解析和生成。
假如我们获取的JSON数据如下:(可以使用curl、fsockopen等方式获取)
{
"translation":["Hello world"],
"query":"你好世界",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"你好世界"
},
{
"value":["Hello World"],
"key":"世界你好"
}
]
}
用json_decode函数返回array的方式得到:
Array ( [translation] => Array ( [0] => Hello world ) [query] => 你好世界 [errorCode] => 0 [web] => Array ( [0] => Array ( [value] => Array ( [0] => hello world ) [key] => 你好世界 ) [1] => Array ( [value] => Array ( [0] => Hello World ) [key] => 世界你好 ) ) )
我们在PHP语言中可以用以下方法取得我们想要的值:
<?php
/*----------------------------------
$data = '
{
"translation":["Hello world"],
"query":"你好世界",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"你好世界"
},
{
"value":["Hello World"],
"key":"世界你好"
}
]
}
';
-------------------------------------*/
$data = <<<STR
{
"translation":["Hello world"],
"query":"你好世界",
"errorCode":0,
"web":[
{
"value":["hello world"],
"key":"你好世界"
},
{
"value":["Hello World"],
"key":"世界你好"
}
]
}
STR;
$jsondata=json_decode($data,true);
header("Content-Type: text/html; charset=UTF-8");
//print_r($jsondata);
echo "<br />".$jsondata['translation'][0]; //Hello world
echo "<br />".$jsondata['query']; //你好世界
echo "<br />".$jsondata['web'][0]['value'][0]; //hello world
echo "<br />".$jsondata['web'][1]['key']; //世界你好
?>