hja*_*001 18 php arrays json file-get-contents
我试图使用杂志api获取以下json内容.json的输出是这样的.我希望下面的json转换为php数组.
{
"bpath": "http://www.sampledomain.com/",
"clist": [
{
"cid": "11",
"display_type": "grid",
"ctitle": "abc",
"acount": "71",
"alist": [
{
"aid": "6865",
"adate": "2 Hours ago",
"atitle": "test",
"adesc": "test desc",
"aimg": "",
"aurl": "?nid=6865",
"weburl": "news.php?nid=6865",
"cmtcount": "0"
},
{
"aid": "6857",
"adate": "20 Hours ago",
"atitle": "test1",
"adesc": "test desc1",
"aimg": "",
"aurl": "?nid=6857",
"weburl": "news.php?nid=6857",
"cmtcount": "0"
}
]
},
{
"cid": "1",
"display_type": "grid",
"ctitle": "test1",
"acount": "2354",
"alist": [
{
"aid": "6851",
"adate": "1 Days ago",
"atitle": "test123",
"adesc": "test123 desc",
"aimg": "",
"aurl": "?nid=6851",
"weburl": "news.php?nid=6851",
"cmtcount": "7"
},
{
"aid": "6847",
"adate": "2 Days ago",
"atitle": "test12345",
"adesc": "test12345 desc",
"aimg": "",
"aurl": "?nid=6847",
"weburl": "news.php?nid=6847",
"cmtcount": "7"
}
]
},
]
}
Run Code Online (Sandbox Code Playgroud)
我的代码看起来像这样.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Run Code Online (Sandbox Code Playgroud)
上面的代码返回一个空数组.:(如何将上述JSON转换为php对象数组.我很无奈.
谢谢哈恩
P. *_*ith 21
您提供的JSON示例无效.使用此JSON Validator http://jsonlint.com/在线查看.您需要删除第59行的额外逗号.
你有一个有效的json,你可以使用这个代码将其转换为数组.
json_decode($ json,true);
Array
(
[bpath] => http://www.sampledomain.com/
[clist] => Array
(
[0] => Array
(
[cid] => 11
[display_type] => grid
[ctitle] => abc
[acount] => 71
[alist] => Array
(
[0] => Array
(
[aid] => 6865
[adate] => 2 Hours ago
[atitle] => test
[adesc] => test desc
[aimg] =>
[aurl] => ?nid=6865
[weburl] => news.php?nid=6865
[cmtcount] => 0
)
[1] => Array
(
[aid] => 6857
[adate] => 20 Hours ago
[atitle] => test1
[adesc] => test desc1
[aimg] =>
[aurl] => ?nid=6857
[weburl] => news.php?nid=6857
[cmtcount] => 0
)
)
)
[1] => Array
(
[cid] => 1
[display_type] => grid
[ctitle] => test1
[acount] => 2354
[alist] => Array
(
[0] => Array
(
[aid] => 6851
[adate] => 1 Days ago
[atitle] => test123
[adesc] => test123 desc
[aimg] =>
[aurl] => ?nid=6851
[weburl] => news.php?nid=6851
[cmtcount] => 7
)
[1] => Array
(
[aid] => 6847
[adate] => 2 Days ago
[atitle] => test12345
[adesc] => test12345 desc
[aimg] =>
[aurl] => ?nid=6847
[weburl] => news.php?nid=6847
[cmtcount] => 7
)
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
你JSON不是一个有效的字符串,正如P. Galbraith上面告诉你的那样.
这是解决方案.
<?php
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Run Code Online (Sandbox Code Playgroud)
使用此代码它将适合您.
| 归档时间: |
|
| 查看次数: |
109613 次 |
| 最近记录: |