1

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
kexxcream
  • 5,873
  • 8
  • 43
  • 62
  • @kerbholz Is it possible to just write the values from JSON? If so, how? Now the data file is always empty. – kexxcream Sep 18 '18 at 07:27
  • The question is not related to `JSON` in any way. – axiac Sep 18 '18 at 07:29
  • That JSON you show, where is that? What variable is it in? You seem to JSON-decode `$_POST['uid']`, so is `$_POST['uid']` a JSON string? Then what does that have to do with the first JSON sample you show? `$_POST` can't be a JSON string… this is very confusing. – deceze Sep 18 '18 at 07:33
  • @deceze I have added a clarification how the data is posted to PHP. I provided an example how the data looks like. – kexxcream Sep 18 '18 at 07:38

3 Answers3

3

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";
}

https://3v4l.org/ekAUB

Result:

uid: 1
questionsid: 1, val: 1
questionsid: 2, val: 1
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • This works very well, but for some reason the data is not received. I send the data like this: `xmlhttp.send("data=" + JSON.stringify({uid, selected}));` and receive it like this: `$_POST = json_decode($_POST['data'], true);` – kexxcream Sep 18 '18 at 08:09
  • check the value of `file_get_contents('php://input')` and adapt your code.. because your using `"Content-Type", "application/json` it wont be in POST, you added that after your orig question. – Lawrence Cherone Sep 18 '18 at 08:15
  • Excellent, the solution was `$json = file_get_contents('php://input');` and then `$_POST = json_decode($json, true);` – kexxcream Sep 18 '18 at 08:35
0

You could make the contents of your file JSON (it's there for a purpose);

Then you simply manipulate the file-array:

$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' ]; 

}

You will end up with an array like:

  [
    uid => 1,
    questions [
       1 => 1,
       2 => 1
       ]
  ]

And write it back in JSON format:

// Write the contents back to the file
file_put_contents($file, json_encode($current,true) );
Michel
  • 4,076
  • 4
  • 34
  • 52
-1

The file_put_contents() writes a string to a file. and what you are doing is trying to write an array to the file. So you need to call it every time or you can serialize the array before saving the data

file_put_contents($file, serialize($array));

or

foreach ($answers as $item) {
    $current .= $item . "\n";
    file_put_contents($file, $item);
}
Exterminator
  • 1,221
  • 7
  • 14