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
4
  • @kerbholz Is it possible to just write the values from JSON? If so, how? Now the data file is always empty. Commented Sep 18, 2018 at 7:27
  • The question is not related to JSON in any way. Commented Sep 18, 2018 at 7: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. Commented Sep 18, 2018 at 7:33
  • @deceze I have added a clarification how the data is posted to PHP. I provided an example how the data looks like. Commented Sep 18, 2018 at 7:38

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

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);
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.
Excellent, the solution was $json = file_get_contents('php://input'); and then $_POST = json_decode($json, true);
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) );

Comments

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

5 Comments

file_put_contents " This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file. "
I didn't say he is using the wrong approach, I am saying you can use the alternative approach.
so, your answer is not related to the issue in anyway!
Is it okay now? @hassan
@Exterminator your edit is even worse, since by default file_put_contents will overwrite the file every time it's called.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.