我有JSON对象,我编码如此
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
我正在获取此JSON数据并将其存储在类似
的文件中File::put("path","var tour = \n [ \n\t $JSONData \n ];");
在文件
中看起来像这样 var tour =
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
现在我正在从第二行开始阅读它,如此
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
问题是,当我想要将其解码回来时它并没有发生,这就是我试图这样做的方式,
$lines = file_get_contents("path",NULL,NULL,10);
$a = json_decode($lines);
现在根据预期的输出,$ a应该有解码的数据,但是它有空。
有人可以指出错误吗?
答案 0 :(得分:3)
我认为问题是你从文件中读回来的JSON末尾的分号。在尝试json_decode
之前尝试切断它:
$a = json_decode(rtrim($lines, ";"));
答案 1 :(得分:2)
答案 2 :(得分:1)
将是
$str = file_get_contents('http://example.com/example.json/');
$json = json_decode($str, true); // decode the JSON into an associative array
答案 3 :(得分:1)
尝试将数据保存在文件中,如
$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
而不是
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
//读起来像
// Read JSON file
$json = file_get_contents('path');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);