Hi I'm absolutely new to php and want to store a json-object from javascript as a .csv file via php.
I have a JSON-Object, defined in a File called Logger.json:
{
"Name": "Dummy",
"Uhrzeit": "1234",
"Speed": "100",
"Level": "11",
"Szenen": {
}
}
After reading the file in via $.getJson, I add some properties to the object. Logger.php now receives the content (first it has always been empty, because i missed json_decode($_POST['data'], true);
the boolean true at the end), but the stored .csv just contains ("Array, Array").
I've also tried other content-types, just sending the jsonText (without data=) or the object obj itself. Any ideas why it won't work? Thanks!
$.getJSON('xml/Logger.json', function(obj) {
//add new scene:
obj.Szenen["144"] = {};
obj.Szenen["144"]["happy"] = {};
obj.Szenen["144"]["happy"].type = "right";
obj.Szenen["144"]["happy"].collected = "0";
obj.Szenen["144"]["sad"] = {};
obj.Szenen["144"]["sad"].type = "false";
obj.Szenen["144"]["sad"].collected = "0";
obj.Szenen["144"]["angry"] = {};
obj.Szenen["144"]["angry"].type = "false";
obj.Szenen["144"]["angry"].collected = "0";
obj.Szenen["200"] = {};
obj.Szenen["200"]["happy"] = {};
obj.Szenen["200"]["happy"].type = "right";
console.log(obj);
var jsonText = JSON.stringify(obj);
var request= new XMLHttpRequest();
request.open("POST", "http://localhost/logger.php")
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded", true)
var data = "data="+jsonText;
request.send(data);
My logger.php looks like this:
<?php
$values = json_decode($_POST['data'], true);
store($values);
function store($data) {
$file = 'logs/UserLogging';
$filename = $file."_".date("d-m-Y_H-i",time()).".csv";
$fp = fopen($filename, 'w');
foreach($data as $line){
//$val = explode(",",$line);
fputcsv($fp, $line);
}
fclose($fp);
}
?>
Edit: The .csv should somehow look like this (but if the keys like "Name" or "Uhrzeit" would also appear in the output, it would be perfect) :
Dummy,1234,100,11;
144,happy,right,0,sad,false,0,angry,false,0;
200,happy,right ...