Записать данные JSON в текстовый файл с помощью PHP
Проблема:
У меня есть скрипт, который отправляет данные 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}));
Проблема в том, что данные JSON не записываются в текстовый файл с помощью функции PHP file_put_contents()
,
Минимальный (рабочий) пример:
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 . "\n";
foreach ($answers as $item) {
$current .= $item . "\n";
}
// 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
3 ответа
Ваш ввод - 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\n";
foreach ($answers as $item) {
$line = '';
foreach ($item as $key => $value) {
$line .= "$key: $value, ";
}
$current .= rtrim($line, ', ')."\n";
}
Результат:
uid: 1
questionsid: 1, val: 1
questionsid: 2, val: 1
Вы можете сделать содержимое вашего файла JSON
(это там с целью);
Затем вы просто манипулируете файлом-массивом:
$postarray= your $_POST JSON ;
//read and decode the file
$current = json_decode( file_get_contents($file) , true );
//SET ID FROM THE POST JSON
$current['uid']=$postarray[$uid];
//LOOP THE POST QUESTION AND PUT THEM IN THE ARRAY
foreach($postarray['selected'] as $q){
$current[ 'question' ][ $q[ 'questionsid' ] ]= $q[ 'val' ];
}
В итоге вы получите массив вроде:
[
uid => 1,
questions [
1 => 1,
2 => 1
]
]
И запишите это обратно в формате JSON:
// Write the contents back to the file
file_put_contents($file, json_encode($current,true) );
file_put_contents()
записывает строку в файл. и то, что вы делаете, пытается записать массив в файл. Поэтому вам нужно вызывать его каждый раз, или вы можете сериализовать массив перед сохранением данных.
file_put_contents($file, serialize($array));
или же
foreach ($answers as $item) {
$current .= $item . "\n";
file_put_contents($file, $item);
}