我有一個應用程序顯示一個網站列表和一些基於JSON文件的信息。我試圖讓應用程序的用戶可以通過自己的網頁添加新的網站列表。PHP - 試圖讓json_encode添加逗號和括號
我遇到的問題是,當我使用JSON_ENCODE時,它附加的JSON文件上沒有開頭或者右括號 - 並且沒有逗號分隔每個對象。
我的應用程序不會讀取沒有添加這些字符的JSON文件。我做了大量的研究,並且在這一天裏我的頭撞牆了幾天。我對PHP非常陌生,所以請原諒我,如果這已經得到了答覆,但我已經搜索,沒有運氣。
這是我的PHP代碼:
<?php
if(isset($_POST['age']) && isset($_POST['id']) && isset($_POST['image']) && isset($_POST['name']) && isset($_POST['snippet0']) && isset($_POST['snippet1'])
&& isset($_POST['snippet3']) && isset($_POST['snippet4']) && isset($_POST['snippet5']) && isset($_POST['snippet6'])) {
if(empty($_POST['age']) || empty($_POST['id']) || empty($_POST['image']) || empty($_POST['name']) || empty($_POST['snippet0']) || empty($_POST['snippet1'])
|| empty($_POST['snippet2']) || empty($_POST['snippet3']) || empty($_POST['snippet4']) || empty($_POST['snippet5']) || empty($_POST['snippet6'])) {
echo 'All fields are required';
}
else {
$postArray = array(
"age" => $_POST['age'],
"id" => $_POST['id'],
"image" => $_POST['image'],
"name" => $_POST['name'],
"snippet0" => $_POST['snippet0'],
"snippet1" => $_POST['snippet1'],
"snippet2" => $_POST['snippet2'],
"snippet3" => $_POST['snippet3'],
"snippet4" => $_POST['snippet4'],
"snippet5" => $_POST['snippet5'],
"snippet6" => $_POST['snippet6']
);
$jsondata = json_encode ($postArray, JSON_PRETTY_PRINT);
$file = 'data/formdata.json';
if(file_put_contents($file, $jsondata, FILE_APPEND)) echo 'Data saved';
else echo 'Unable to save data';
}
}
else echo 'Form fields not submitted';
?>
下面是JSON輸出的一個例子,我得到它:
{
"age": "1",
"id": "bob",
"image": "bob.png",
"name": "Bob.com",
"snippet0": "sub.bob.com",
"snippet1": "sub.bob.com",
"snippet2": "sub.bob.com",
"snippet3": "sub.bob.com",
"snippet4": "sub.bob.com",
"snippet5": "sub.bob.com",
"snippet6": "sub.bob.com"
}{
"age": "1",
"id": "bob",
"image": "bob.png",
"name": "Bob.com",
"snippet0": "sub.bob.com",
"snippet1": "sub.bob.com",
"snippet2": "sub.bob.com",
"snippet3": "sub.bob.com",
"snippet4": "sub.bob.com",
"snippet5": "sub.bob.com",
"snippet6": "sub.bob.com"
}
最後,JSON輸出的一個例子,我想:
[{
"age": "1",
"id": "bob",
"image": "bob.png",
"name": "Bob.com",
"snippet0": "sub.bob.com",
"snippet1": "sub.bob.com",
"snippet2": "sub.bob.com",
"snippet3": "sub.bob.com",
"snippet4": "sub.bob.com",
"snippet5": "sub.bob.com",
"snippet6": "sub.bob.com"
},{
"age": "1",
"id": "bob",
"image": "bob.png",
"name": "Bob.com",
"snippet0": "sub.bob.com",
"snippet1": "sub.bob.com",
"snippet2": "sub.bob.com",
"snippet3": "sub.bob.com",
"snippet4": "sub.bob.com",
"snippet5": "sub.bob.com",
"snippet6": "sub.bob.com"
}]
file_put_contents從文件中獲取JSON之前,使用'json_decode',添加新值,使用'json_encode',並運行'file_put_contents'沒有FILE_APPEND – 2015-01-20 19:19:19
我需要什麼值增加對json_decode? – blasted 2015-01-20 19:39:04
新數據 - $ postArray – 2015-01-20 19:41:19