用PHP将JSON数据写入文本文件
问题:
我有一个脚本,它以这种方式将JSON数据发送到PHP文件:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "process-survey.php");
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({uid, selected}));
问题是未使用PHP函数file_put_contents()
将JSON数据写入文本文件。
最小(工作)示例:
控制台日志中的JSON
{
"uid":1,
"selected":[
{
"questionsid":1,
"val":"1"
},
{
"questionsid":2,
"val":"1"
}
]
}
PHP
<?php
$uid = json_decode($_POST['uid'], true);
$answers = json_decode($_POST['selected'], true);
$file = $_SERVER['DOCUMENT_ROOT'] . '/association/data.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new id to the file
$current .= $uid . "
";
foreach ($answers as $item) {
$current .= $item . "
";
}
// Write the contents back to the file
file_put_contents($file, $current);
?>
权限
添加了以下读/写功能:chmod 644 data.txt
所需输出:
uid: 1
questionid: 1, val: 1
questionid: 2, val: 1
解决方案
您的输入是json,所以它还没有被分成uid
,selected
,所以下面的代码将获取您的json并输出您预期的结果(我想这就是您的意思,将其放在$_POST
中)。
<?php
$json = '{
"uid":1,
"selected":[
{
"questionsid":1,
"val":"1"
},
{
"questionsid":2,
"val":"1"
}
]
}';
$_POST = json_decode($json, true);
$uid = $_POST['uid'];
$answers = $_POST['selected'];
$current = ''; // fgc
// start building your expected output
$current .= "uid: $uid
";
foreach ($answers as $item) {
$line = '';
foreach ($item as $key => $value) {
$line .= "$key: $value, ";
}
$current .= rtrim($line, ', ')."
";
}
https://3v4l.org/ekAUB
结果:
uid: 1
questionsid: 1, val: 1
questionsid: 2, val: 1
相关文章