我有这个JSON:
{
"cache": true,
"data": [
{
"unique_id": "914239",
"description": "New Zealand 370/10 & 335/10 v Australia 70/1 & 505/10 *",
"title": "New Zealand 370/10 & 335/10 v Australia 70/1 & 505/10 *"
},
{
"unique_id": "973833",
"description": "Helmand Province Under-17s 135/10 * v Khost Province Under-17s 286/9 ",
"title": "Helmand Province Under-17s 135/10 * v Khost Province Under-17s 286/9 "
},
{
"unique_id": "935949",
"description": "Mid West Rhinos v Mashonaland Eagles 264/2 *",
"title": "Mid West Rhinos v Mashonaland Eagles 264/2 *"
},
{
"unique_id": "973379",
"description": "Mountaineers 136/10 v Matabeleland Tuskers 42 *",
"title": "Mountaineers 136/10 v Matabeleland Tuskers 42 *"
},
{
"unique_id": "959221",
"description": "Islamabad United v Quetta Gladiators",
"title": "Islamabad United v Quetta Gladiators"
}
],
"provider": {
"pubDate": "2016-02-23T14:01:01.467Z",
"source": "http://www.cricinfo.com/",
"url": "http://crm.wherrelz.com/"
}
}
我需要在我的PHP网站上显示标题和数据。
答案 0 :(得分:1)
非常简单:
$raw_json = file_get_contents('data.json');
$array = json_decode($raw_json);
foreach ($array->data AS $data) {
echo $data->title;
echo '<br />';
echo $data->description;
echo '<br />';
}
文件data.json
当然包含你的json。
答案 1 :(得分:1)
您可以使用json_decode
解码数据,您可以在此处找到完整的文档:http://php.net/manual/en/function.json-decode.php
就代码示例而言,您可以执行以下操作:
$decoded = json_decode($json);
if (json_last_error() !== JSON_ERROR_NONE) {
// Do something when you don't have valid json.
}
foreach ($decoded->data as $data) {
echo $data->unique_id;
echo $data->title;
}
json_last_error()
将允许您捕获任何无效的JSON或json_decode()
可能遇到的任何其他潜在错误,因此我绝对建议使用它并确保您在执行之前已经解码了有效的json任何事情。