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];
?>
Related
I was given a task to sort out data from a text file into JSON using PHP and object oriented principal.
The text file has information and is displayed as follows (ignore #):
#product_num:name:cost
5:tv:59.99
7:radio:10.99
I created a class and in this class I have one function that ignores any # or blank spaces from the data and puts the data in an array and json_encode it. When I echo this data it looks like this:
[{"1":"5:tv:59.99","2":"7:radio:10.99"}]
Is it possible to write other functions to separate the data further, for example so it looks more like:
[{"product_number":"5","name":"tv","cost":"59.99"},{"product_number":"7","name":"radio","cost":"10.99"}]
If so can anyone give me any pointers and tips because I have no idea where or how to begin even after numerous google searches.
There is a function inside PHP for reading value separated lines, like CSV; it's called fgetcsv which can also be used in object oriented PHP through SplFileObject::fgetcsv.
You will need to read each line, add the variable labels then append that to an array.
Depending on the size of the file you may need to optimize for memory usage as your array grows by saving as you proceed through the file.
<?php
$file = new SplFileObject('test.txt', 'r'); //Load the file
$file->current(); //Skip the first line (Side note: seek(1) did not appear to work while testing)
$result = [];
do { //While there are lines in the file
list($product_num, $name, $cost) = $file->fgetcsv(':'); //Break the line on the : delimiter into an array and populate the array into the three named values
$result[] = [ //Build the new json representation and add to result array
'product_num' => $product_num,
'name' => $name,
'cost' => $cost,
];
} while (!$file->eof());
file_put_contents('output.json', json_encode($result)); //Save the result
Your file format is basically a csv file and PHP has a CSV import function.
http://php.net/manual/en/function.fgetcsv.php
If you scroll down and check the CsvImporter example, you can copy/paste that and add a json_encode:
$importer = new CsvImporter("small.txt",true,":");
$data = $importer->get();
echo json_encode($data);
[{
"\ufeff#product_num": "5",
"name": "tv",
"cost": "59.99"
},
{
"\ufeff#product_num": "7",
"name": "radio",
"cost": "10.99"
}]
I'm trying to use the google charts api to present power (watt) over time. I have a sqlite database in which i store my data. A php script then gathers the data and outputs it into a json file. For the charts to work i need to keep a specific structure. Whenever i run the phpscript the json file gets overwritten with the new data. I need help with the php script to always output the data according to googles parameters.
I'm aiming to end up with an area chart that plots power on the y axis and the datestamps on the x axis.
I've read theese documents in googles documentation but i can't figure out how to output the data the way they do.
https://developers.google.com/chart/interactive/docs/php_example
https://developers.google.com/chart/interactive/docs/reference#dataparam
while ($res = $stmt->fetch(PDO::FETCH_ASSOC)){
$voltage[] = $res['voltage'];
$current[] = $res['current'];
$datestamp[] = $res['datestamp'];
}
$unixtimestamp = array();
foreach ($datestamp as $nebulosa){
$unixtimestamp[] = strtotime($nebulosa);
}
$power = array();
foreach ($voltage as $key => $door){
$power[] = $door * $current[$key];
}
//echo "<pre>", print_r($power, true), "</pre>";
$fp = fopen('data.json', 'w');
fwrite($fp, json_encode($power));
fwrite($fp, json_encode($datestamp));
fclose($fp);
The json file has this format after running the php script.
[3.468,5]["2016-10-14 14:56:22","2016-10-14 14:56:23"]
I have a python script and a PHP page on my website. I have to create a csv file and write the data onto it in following manner-
PHP processes the GET requests and calls the python script by shell_exec, passing the GET variables into it, is JSON format. The script here looks like-
...
$var_a = $_GET['a'];
$var_b = $_GET['b'];
$var_c = $_GET['c'];
$post_data = array('item' => 'get-list',
'var a' => "$var_a",
'var b' => "$var_b",
'var c' => "$var_c"
);
$json_data = json_encode($post_data);
$temp = shell_exec('python process_data.py "' . $json_data .'"');
echo $temp;
...
This script is quite straight forward, which does simply collects the GET variables and forms JSON object of it. Now this data is passed to process_data.py, which processes the data and saves the data into a csv file, the code for which is-
import sys, json, time, csv
json_data = json.dumps(sys.argv[1])
def scr(json_data):
json_data = json_data
count = 0
json_list = json_data.split(',')
for i in json_list:
count=count+1
if(count==5):
lati = json_list[0].strip('{')
longi = json_list[1]
datestmp = json_list[2]
timestmp = json_list[3]
out = open('file.csv', 'w')
out.write('%s;' % lati.split(':')[1])
out.write('\n')
out.write('%s;' % longi.split(':')[1])
out.write('\n')
out.write('%s;' % datestmp.split(':')[1])
out.write('\n')
out.write('%s;' % timestmp.split(':',1)[1])
out.write('\n')
out.close()
print 'Latitude: ',lati.split(':')[1],', Longitude: ',longi.split(':')[1],', Datestamp: ',datestmp.split(':')[1],', Time: ', timestmp.split(':',1)[1]
else:
print 'Wrong data received'
scr(json_data)
All the things are working well. The data is processed and saved. The PHP script also saves the current data into database. So PHP does two operations-
1. Saves the data into database
2. Pass the data to python script which saves the data into CSV file.
However, the GET data is coming at regular time-interval(say 1 or 2 seconds). So, the call to Python file gets regular for these intervals. It will have to open the CSV file every 1-2 seconds, write the data there. This will slow down the processing.
I want the CSV file to remain open till the data is coming, and close it when the GET request is not made for a long time. Is there any way to do so?
My Flash movie reads and sends data to a PHP file in a free server. It seems ok for Flash to read variable values from a text file (which is managed by a PHP file) if they are wrote in this way: &variable = value&, I have no problem with that.
But my PHP file, pre-treated (by some mathematical functions) data sent by Flash and then, updates the values in the text file, that is my intention but I can't accomplish it.
Suppose I want to update a counter ( it counts how many times the data were updated):
in the text file I have &counter=0& (initial value) and if I put in the PHP file:
<?php
$fp = fopen("jose_stats.txt", "r");// I guess with it, I've read all the variables and values
// one of them is the variable &counter.
fclose($fp);
$toSave = "&counter=&counter+1&\n";
$fp = fopen("jose_stats.txt", "w");
if(fwrite($fp, "$toSave")) {
echo "&verify=success&"; //prints to screen &verify=success which flash will read
//and store as myVars.verify
} else { // simple if statement
echo "&verify=fail&"; //prints to screen &verify=fail which flash will read and
//store as myVars.verify
}
fclose($fp);
?>
but then, I check my text file and it has &counter=&counter+1& line :( and not the expected &counter =1&.
Please, give me and advise. Thank you.
Why not use JSON?
Just store the data in JSON format:
$count = 1;
$toWrite = array( 'count' => $count );//put other data into this array if you want
//encode it
$toWrite = json_encode( $toWrite );
//and now write the data
To decode it in flash, import the JSON class:
An example of JSON in as2 using the JSON.as class:
try {
var o:Object = JSON.parse(jsonStr);
var s:String = JSON.stringify(obj);
} catch(ex) {
trace(ex.name + ":" + ex.message + ":" + ex.at + ":" + ex.text);
}
So just import the class, and run JSON.parse( yourPhpResponse );.
Also, the reason for why you're seeing &counter=& in the text file is because you're storing it like that: $toSave = "&counter=&counter+1&\n";.
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));