Decode and update a JSON array in PHP - php

I need to update my JSON array in the file jsonData_0_123.json. I can get the data from the file and decode it, but I can't update the data in the file (in this case, the array answers)
$contents = file_get_contents('json_files/jsonData_0_123.json');
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true);
//Update the decoded array
$contentsDecoded[1]["answers"] = "hello";
//Encode the array back into a JSON string.
$json = json_encode($contentsDecoded);
//Save the file.
file_put_contents('json_files/jsonData_0_123.json', $json);

I tried your code it is updating in json file with array answers.I found problem with file permission error for (jsonData_0_123.json) writing data into it.Otherwise it's working fine.

Related

Generate JSON files for Hightcharts with PHP from a TCP string

I need to generate 2 JSON files with PHP from 2 TCP commands in order to build a Highchart graph.
The first JSON file will contain the graph informations :
Graph Title, Graph Subtitle, Y axis title and a number related to the type of graph to be displayed.
The TCP string (from an IoT distant board) sends to the server the following arguments :
Name of JSON info file to built
Graph Title
Graph Subtitle
Graph Y axis title
Type of graph to be displayed
http:myserver/graphs/make-json_info.php?jsonfilename=S_007_nfo.json&graphtitle=S_007_Sensor&graphsubtitle=Office-Temp&Yaxistitle=Temp-Sensor&GraphType=3
How could i make a JSON file with a PHP file named 'make-json_info.php' from this TCP string ?
JSON file should look like this :
{
chart: {
type: '/*...*/'
},
xAxis: {/*...*/},
yAxis: {/*...*/},
plotOptions: {/*...*/}
/*...etc...*/
}
Regarding the 2sd JSON file needed to generate the graph, the IoT board sends every minutes another TCP string that contains :
Name of JSON data file to fill-in
Datetime stamp
Sensor value
http:myserver/graphs/make-json_data.php?S_007_data.json&datatime=1488271800000&value=22.5
Expected JSON file should be like this :
http://s529471052.onlinehome.fr/graphs/S_007_data.json
Can you show me how to write my two PHP files, these should generate 2 JSON files in order to built the expected Highcharts Graph afterwards ?
So far, i tried to extract informations from the JSON data file and JSON info file fro graph information is missing.
see jsfiddle below
http://jsfiddle.net/fbmohjgy/
I'm uncertain about many things in you question, but I will try my best.
The JSON file that contain the graph information... Does it only contain meta infromation about the graph (title, type, etc), or does the file also contains xAxis Data and yAxis Data...
From these two lines in your question, it seems like it may also contains the actual data:
xAxis: {/*...*/},
yAxis: {/*...*/},
Apologies if I got it all wrong, but this is what I came up with.
It is not tested, but should give you an idea of what to do:
Let's start with the second file/script first.
<?php
$file_name = $_GET['jsonfilename'];
$datatime = $_GET['datatime'];
$value = $_GET['value'];
$file_content = file_get_contents($file_name); //read data from json file
$temp_file_data = json_decode($file_content, true); //convert json string into php array
$temp_file_data['date'][] = [$datatime, $value]; //add your new values to the array
$new_file_content = json_encode($temp_file_data); //encode your new array as a json string
file_put_contents($file_name, $new_file_content); //save the new json string back to the file
?>
Now for the first PHP script. This script will use the json file from the above code to create the complete json file that the graph will use:
<?php
$file_name = $_GET['jsonfilename'];
$graphtitle = $_GET['graphtitle'];
$graphsubtitle= $_GET['graphsubtitle'];
$Yaxistitle= $_GET['Yaxistitle'];
$GraphType = $_GET['GraphType'];
$data_json = file_get_contents($file_name); //read data from json file
$data_array = json_decode($file_content, true); //convert json string into php array
$xAxis = []; //create array that will contain all xAxis values
$yAxis = []; //create array that will contain all yAxis values
for($i = 0; $i < sizeof($data_array['data']); $i++)
{
$xAxis[] = $data_array['data'][$i][0]; //add xAxis data from first json file to the xAxis array
$yAxis[] = $data_array['data'][$i][1]; //add yAxis data from first json file to the yAxis array
}
$json_array = []; //declare the array that will be converted to the final JSON string that the graph will use
$json_array['chart'] = ['type' => $GraphType];
$json_array['xAxis'] = $xAxis;
$json_array['yAxis'] = $yAxis;
$json_array['plotOptions'] = ['graphtitle' => $graphtitle,
'graphsubtitle' => $graphsubtitle,
'Yaxistitle' => $Yaxistitle];
?>

How to get blob data in json or xml format?

I have stored xml file in mysql BLOB datatype,so now i want to get that data in xml or json format and need to display.
i tried like this,but getting binary values
$mqs = db_select('multiple','mq')
->fields('mq',array('data'))
->condition('tokenid', '1')
->execute();
foreach ($mqs as $row) {
$test = base64_encode($row->surveyid); //here junk binary data displaying
drupal_set_message("data ::".$test);
$xml = simplexml_load_string($test);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
drupal_set_message("data::".$json);
}
actual data not displayed in XML or JSON formats?
any other alternatives?

How to Overwrite Json if Fields Match - PHP

Working on a website and need to store data for each user. Currently using json files and the way it is set up currently it overwrites the data each time.
1st question, is using one json file the best way to house this data or should I set up a directory for each user?
2nd question, if one file is the best way to go, how do I append 'unique' data? I found some example code from the posts on "Overwrite JSON if fields match PHP" but it is not working for me. It is not writing to the file at all now.
Original code:
$posts[] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat);
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Revised code to be able to append new data and eliminate redundancies(Does not work):
$file = file_get_contents('results.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[vhclID] = array('vhclID'=> $vhclID, 'statVal1'=> $engStat,
'statVal2'=> $brakeStat);
//save the file
$data = array_values($data);
file_put_contents('results.json',json_encode($data));
echo json_encode($data);
unset($data);//release memory
Thanks for your help!!
You should use a database if you're storing typical user data; clearly you don't want to load megabytes of user data just to observer or modify one field for one user.
If you have some posted data, and I understand your question correctly, you might do something like this (but add more security):
$new_data = $_POST[];
foreach ($new_data as $name=>$datum) {
if (empty($data[vhclID][$name]) {
// This means that this field is unique
$data[vhclID][$name] = $datum;
}
}
And then just save that data to your JSON file.
$fp = fopen('results.json', 'r');
$postjson = json_decode(fread($fp, 1024*1024), true);
fclose($fp);
$posts = ($posts==array()) array('vhclID'=> $vhclID, 'statVal1'=> $engStat, 'statVal2'=> $brakeStat) : $postjson['posts'];
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Should do what you want.
Modify $posts.
I mess around with PHP and json data a lot.
One thing I've noticed is that json_decode will create a PHP object(stdClass) by default
Example
Contents of results.json >>> {"example":"test"}
$file = file_get_contents("results.json");
$json = json_decode($file);
var_dump($json); // Outputs: object(stdClass)#14 (1) { ["example"]=> string(4) "test" }
If you add true as the second parameter to json_decode you end up with an array instead
Example
$file = file_get_contents("results.json");
$json = json_decode($file, TRUE); // Added TRUE as second parameter
var_dump($json); // Outputs: array(1) { ["example"]=> string(4) "test" }
Once you have your appropriate data, you can modify and change the $json however you want and then re-write it to the .json file.
So for question 1: Having an individual json file for each user (eg: userID-001.json, userID-002.json) is probably the better way to go.
For question 2: You can take the individual file, grab the contents and store it in a PHP array using json_decode($data, TRUE) // with true as second parameter if you want an array and then modify the array and resave it (using json_encode).
Hope this helps~!

How to add to JSON array in .json file

How do I add to a .json file with PHP? Currently, I'm appending a .json file with PHP, but it won't add the data to an existing JSON object. It makes a new object. I need the data all stored in one object, in an external JSON file. Basically, I have a JSON object and want to add more values to it.
$jsonFile = "test.json";
$fh = fopen($jsonFile, 'w');
$json = json_encode(array("message" => $name, "latitude" => $lat, "longitude" => $lon, "it" => $it));
fwrite($fh, $json);
You can decode the json file to a php array, then insert new data and save it again.
<?php
$file = file_get_contents('data.json');
$data = json_decode($file);
unset($file);//prevent memory leaks for large json.
//insert data here
$data[] = array('data'=>'some data');
//save the file
file_put_contents('data.json',json_encode($data));
unset($data);//release memory
what's suggested above is the hard way. i am considering there should be an easier way, to literally append an array into the json file.
here is the algo:
$handle=fopen($jsonFile);
fseek($handle,-1,SEEK_END);
fwrite($handle,$arrayToAdd);
fclose($handle);
but i am not sure it's more cpu/memory efficient to do so than reading the whole json file into memory, adding the array and then getting it stored.

PHP - How to update JSON data in a txt file?

Here is a JSON data example saved in a file data.txt
[
{"name":"yekky"},
{"name":"mussie"},
{"name":"jessecasicas"}
...// many rows
]
I would like to update the file so it will look like this:
[
{"name":"yekky","num":"1"},
{"name":"mussie","num":"2"},
{"name":"jessecasicas","num":"3"}
...// many rows
]
This is what I have got so far:
$json_data = file_get_contents('data.txt');
// What goes here?
And how do I count how many rows there are in the JSON tree?
Use json_decode() to decode the JSON data in a PHP array, manipulate the PHP array, then re-encode the data with json_encode().
For example:
$json_data = json_decode(file_get_contents('data.txt'), true);
for ($i = 0, $len = count($json_data); $i < $len; ++$i) {
$json_data[$i]['num'] = (string) ($i + 1);
}
file_put_contents('data.txt', json_encode($json_data));
You should use the PHP JSON library for such tasks. For example, after having read your JSON data from the file, do something like:
$json = json_decode($json_data);
$itemCount = count($json);
After having modified your JSON data, just encode it again:
$json_data = json_encode($json);
Also, you seem to want to beatify your JSON data. My advise is to just use whatever comes out of json_encode and save that to your file, because it will probably be the smallest (in file size) possible representation of your JSON data.
If you format it in a way readable for humans, you've got lots of extra spaces / tabs / line-breaks which increase file size and parsing time.
If you need to read it yourself, you can still beautify your JSON data by hand.
$file = 'data.txt';
$data = json_decode(file_get_contents($file));
foreach ($data as $key => $obj) {
$obj->num = (string)($key+1);
}
file_put_contents($file, json_encode($data));

Categories