Write JSON data to text file with PHP [duplicate]

回眸只為那壹抹淺笑 提交于 2021-02-10 19:58:55

问题


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

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

https://3v4l.org/ekAUB

Result:

uid: 1
questionsid: 1, val: 1
questionsid: 2, val: 1



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/52381052/write-json-data-to-text-file-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!