Problem:
I have a script that send JSON data to a PHP file in this way:
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}));
The problem is that JSON data is not written to text file using the PHP function file_put_contents()
.
Minimal (Working) Example:
JSON as in the console log
{
"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);
?>
Permissions
Added the following read/write: chmod 644 data.txt
Desired output:
uid: 1
questionid: 1, val: 1
questionid: 2, val: 1
Your input is json, so it wont already be broken up into parts uid
, selected
, so the following code is taking your json and outputting your expected result (placing it in $_POST
as I presume that's what you mean).
<?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";
}
Result:
uid: 1
questionsid: 1, val: 1
questionsid: 2, val: 1