使用PHP将数据附加到.JSON文件
我有一个.json文件:使用PHP将数据附加到.JSON文件,php,json,Php,Json,我有一个.json文件: [ { "id": 1, "title": "Ben\\'s First Blog Post", "content": "This is the content" }, { "id": 2, "title": "Ben\\'s Second Blog Post", "content": "This is the content" } ] 这是
[
{
"id": 1,
"title": "Ben\\'s First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\'s Second Blog Post",
"content": "This is the content"
}
]
这是我的PHP代码:
<?php
$data[] = $_POST['data'];
$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);
盲目地在json数据中添加文本会破坏json数据。JSON不是一种可以像这样操作的格式
您必须加载json文本,对其进行解码,操作生成的数据结构,然后重新编码/保存它
<?php
$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));
如果您想向JSON文件添加另一个数组元素(如示例所示),请打开该文件并搜索到底。如果文件已经有数据,向后搜索一个字节以覆盖最后一个条目之后的]
,然后写入,
加上新数据减去新数据的初始[
。否则,它是第一个数组元素,所以只需正常写入数组即可
很抱歉,我对PHP了解不够,无法发布实际代码,但我在Obj-C中已经这样做了,它允许我避免先读取整个文件,然后再添加到末尾:
NSArray *array = @[myDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
FILE *fp = fopen(fname, "r+");
if (NULL == fp)
fp = fopen(fname, "w+");
if (fp) {
fseek(fp, 0L, SEEK_END);
if (ftell(fp) > 0) {
fseek(fp, -1L, SEEK_END);
fwrite(",", 1, 1, fp);
fwrite([data bytes] + 1, [data length] - 1, 1, fp);
}
else
fwrite([data bytes], [data length], 1, fp);
fclose(fp);
}
这是上面的c示例,并将其移到php中。这将跳转到文件的末尾并添加新数据,而无需将所有文件读入内存
// read the file if present
$handle = @fopen($filename, 'r+');
// create the file if needed
if ($handle === null)
{
$handle = fopen($filename, 'w+');
}
if ($handle)
{
// seek to the end
fseek($handle, 0, SEEK_END);
// are we at the end of is the file empty
if (ftell($handle) > 0)
{
// move back a byte
fseek($handle, -1, SEEK_END);
// add the trailing comma
fwrite($handle, ',', 1);
// add the new json string
fwrite($handle, json_encode($event) . ']');
}
else
{
// write the first event inside an array
fwrite($handle, json_encode(array($event)));
}
// close the handle on the file
fclose($handle);
}
我用来向JSON文件追加额外JSON数组的示例代码
$additionalArray = array(
'id' => $id,
'title' => $title,
'content' => $content
);
//open or read json data
$data_results = file_get_contents('results.json');
$tempArray = json_decode($data_results);
//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
/*
*@var-temp
*存储info.json文件的值
*/
$temp=file_get_contents('info.json');
/*
*@var-temp
*将json的解码值存储为数组
*/
$temp=json_解码($temp,TRUE);
//在临时数组中推送信息
$temp[]=$information;
//显示要写入的新数据
回声';
打印(临时);
//将内容写入info.json文件
文件内容('info.json',json编码($temp));
}
我编写这段PHP代码是为了将json添加到json文件中。
代码将整个文件括在方括号内,并用逗号分隔代码
$data = $_POST['data'];
//$data=
array("Q"=>"QuestThird","A"=>"AnswerThird");
$inp = file_get_contents('QuesAns.json');
//$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';
/**Convert to array because array_push working with array**/
$tempArray = json_decode($inp,true);
array_push($tempArray, $data);
print_r($tempArray);
echo'<hr>';
$jsonData = json_encode($tempArray);
file_put_contents('QuesAns.json', $jsonData);
print($jsonData);
GoodLuck使用PHP将数据附加到.json
文件
- 还应使用有效的json结构
- 不附加数组
- 将json附加到QuesAns
.json
文件
- 覆盖文件中的数据
$data=$\u POST['data'];
//$data=
数组(“Q”=>“QuestThird”、“A”=>“AnswerThird”);
$inp=file_get_contents('QuesAns.json');
//$inp='[{“Q”:“QuestFurst”,“A”:“AnswerFirst”},{“Q”:“Quest second”,“A”:“AnswerSecond”}];
/**转换为array,因为array_push正在使用array**/
$tempArray=json_decode($inp,true);
数组_push($tempArray,$data);
打印(临时数组);
回声“
”;
$jsonData=json_encode($tempArray);
文件内容('QuesAns.json',$jsonData);
印刷品(jsonData美元);
输出:
数组([0]=>Array([Q]=>QuestFurst[A]=>AnswerFirst)[1]=>Array([Q]=>questsecond[A]=>AnswerSecond[2]=>Array([Q]=>QuestThird[A]=>AnswerThird))
[{“Q”:“QuestFurst”,“A”:“AnswerFirst”},{“Q”:“QuestSecond”,“A”:“AnswerSecond”},{“Q”:“QuestThird”,“A”:“AnswerThird”}]
我不认为JSON是一种增量格式;你必须对它进行反序列化,添加新记录,然后再次序列化它。我知道这不是你问题的答案,但这让我想起了一次我尝试用XML做同样的事情。目的是存储博客文章,我认为这是一种避免需要MySQL的很酷的方法。这,howe事实并非如此。从长远来看,使用数据库而不是文件来处理此类数据更可靠、更好的做法,也更省事。我很抱歉,我知道当你问一个问题,有人回答“不要那样做”时,这会让人非常恼火(这就是为什么我将此作为评论发布的原因)。这正是我希望早点告诉我的。将数据附加到.JSON文件[在此处输入链接描述][1][1]:被解释为数据的文件需要如何格式化才能正常工作?这不是每次都需要更长的时间吗?当你有一个巨大的JSON文件时,这难道不是很可笑吗?我正在处理大量数据。这里是php新手…如果我使用文件内容获取“post数据”,我如何修改上面的答案才能正常工作('php://input“)?所以基本上第一行对我不起作用。我使用的是文件获取内容(”php://input“)因为我在JS中调用fetch()来生成http post。很好的解决方案!最初对我不起作用。必须用$handle==null重新封装$handle==null
/*
* @var temp
* Stores the value of info.json file
*/
$temp=file_get_contents('info.json');
/*
* @var temp
* Stores the decodeed value of json as an array
*/
$temp= json_decode($temp,TRUE);
//Push the information in temp array
$temp[]=$information;
// Show what new data going to be written
echo '<pre>';
print_r($temp);
//Write the content in info.json file
file_put_contents('info.json', json_encode($temp));
}
<?php
//This is the data you want to add
//I am getting it from another file
$callbackResponse = file_get_contents('datasource.json');
//File to save or append the response to
$logFile = "results44.json";
//If the above file does not exist, add a '[' then
//paste the json response then close with a ']'
if (!file_exists($logFile)) {
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists but is empty, add a '[' then
//paste the json response then close with a ']'
else if ( filesize( $logFile) == 0 )
{
$log = fopen($logFile, "a");
fwrite($log, '['.$callbackResponse.']');
fclose($log);
}
//If the above file exists and contains some json contents, remove the last ']' and
//replace it with a ',' then paste the json response then close with a ']'
else {
$fh = fopen($logFile, 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh);
$log = fopen($logFile, "a");
fwrite($log, ','.$callbackResponse. ']');
fclose($log);
}
?>
$data = $_POST['data'];
//$data=
array("Q"=>"QuestThird","A"=>"AnswerThird");
$inp = file_get_contents('QuesAns.json');
//$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';
/**Convert to array because array_push working with array**/
$tempArray = json_decode($inp,true);
array_push($tempArray, $data);
print_r($tempArray);
echo'<hr>';
$jsonData = json_encode($tempArray);
file_put_contents('QuesAns.json', $jsonData);
print($jsonData);