I'm working on a project that needs to add JSON to the file after every form submission.
My goal is to get the JSON to look like:
{
"word0":[
"cheese",
"burger"
],
"word1":[
"sup",
"boi"
],
"word2":[
"nothin'",
"much"
]
}
But I'm not able to add to the JSON file afterwards.
EDIT: I'm thinking about just creating a new file for every form submission. Would this be a better option?
(Storage size isn't a problem)
Here's my current code that places JSON into a file:
$response['word' . $count] = array('word1' => $_POST['firstrow'], 'word2' => $_POST['secondrow']);
file_put_contents("query.json", file_get_contents("query.json") . json_encode($response) . "\n");
Well if you have no problem with storage size you can do a new file for every form submission.
But you can make it one large file via reading the writing the file.
$data = json_decode(file_get_contents("data.json"), true);
$data["word3"] = array("i don't" , "know");
file_put_contents("data.json", json_encode($data));
If you want to save on your IO, you can do writing at a specific position via fseek.
$file = fopen("data.json", "c");
fseek($file, -5, SEEK_END); // 5 character back from the end of the file.
fwrite($file, $newJsonArrayElement);
fclose($file);
^^^^^^^^^^^^^^^^^^^^^^^^^
this is an example snipper, you will need to calculate the characters to seek back from the end and somehow generate the new json.
Related
I am doing a chunk file upload to a server and I am interested in such a thing as determining whether this file has changed.
Suppose I send a file of size 5 mb. The size of one chunk is 1 mb. 4 chunks are sent to the server, and the last one did not go because of a broken connection.
After the document was changed at the beginning and the first chunk of this document no longer matches the first chunk on the server, the last chunk is loaded, but the contents are already different.
In order to determine that one of the chunks has been changed, you need to re-send all the chunks to the server to get the hash of the amount, but then the whole load loses its meaning.
How can I determine that a file has been modified without sending all the chunks to the server?
Additionally:
Uploading files is as follows:
First, the browser sends a request to create a new session for uploading files.
Request params:
part_size: 4767232
files: [
{
"file_size":4767232,
"file_type":"application/msword",
"file_name":"5 mb.doc"
}
]
Next:
New records about uploaded files are added to the database.
The server creates temporary folders for storing chunks.
(Folder name is the guids of the file record created by the database.)
The method returns file guids.
After receiving the guids, the browser divides the files into chunks using the JavaScript Blob.slice() method and sends each chunk as a separate request, attaching the file identifier to the request.
Chunks are saved and after the last chunk has been uploaded the file is collected.
Code:
/**
* #param $binary - The binary data.
* #param $directory - Current file with chunks directory path.
*/
private static function createChunk($binary, $directory)
{
//Create a unique id for the chunk.
$id = 'chunk_' . md5($binary);
// Save the chunk to dad with the rest of the chunks of the file.
Storage::put($directory . '/' . $id, $binary);
// We get a json file with information about uploading session.
$session = self::uploadSessionInfo($directory);
// Increase the number of loaded chunks by 1 and add a new element to the subarray chunks.
$session['chunks_info']['loaded_chunks'] = $session['chunks_info']['loaded_chunks'] + 1;
$session['chunks_info']['chunks'][] = [
'chunk_id' => $id
];
// Save the modified session file.
Storage::put($directory . '/session.json', json_encode($session));
// If the number of loaded chunks and the number of total chunks are the same, then we create the final file.
if ($session['chunks_info']['total_chunks'] === $session['chunks_info']['loaded_chunks']) {
Storage::put($directory . '/' . $session['file_name'], []);
foreach ($session['chunks_info']['chunks'] as $key => $value) {
$file = fopen(storage_path() . '/app/' . $directory . '/' . $value['chunk_id'], 'rb');
$buff = fread($file, 2097152);
fclose($file);
$final = fopen(storage_path() . '/app/'. $directory . '/' . $session['file_name'], 'ab');
$write = fwrite($final, $buff);
fclose($final);
}
}
}
Visually looks like this:
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"
}]
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~!
I'm relatively new to PHP and I'm trying to get a small script running. I have a VB .net program that posts data using the following function.
Public Sub PHPPost(ByVal User As String, ByVal Score As String)
Dim postData As String = "user=" & User & "&" & "score=" & Score
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.ContentLength = byteData.Length
Dim postReqStream As Stream = postReq.GetRequestStream()
postReqStream.Write(byteData, 0, byteData.Length)
postReqStream.Close()
End Sub
Where "myphpscript" is acutally the full URL to the PHP script. Basically I'm trying to POST the "User" variable and the "Score" variable to the PHP script. The script I've tried is as follows:
<?php
$File = "scores.rtf";
$f = fopen($File,'a');
$name = $_POST["name"];
$score = $_POST["score"];
fwrite($f,"\n$name $score");
fclose($f);
?>
The "scores.rtf" does not change. Any help would be appreciated. Thanks ahead of time, I'm new to PHP.
Ensure that your script is receiving the POST variables.
http://php.net/manual/en/function.file-put-contents.php
You can try file_put_contents, it combines the use of fopen ,fwrite & fclose.
It could be wise to use something like isset/empty to check that there is something to write before writing.
<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);
//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also, totally overlooked the RTF part, definitely look into what Mahan mentioned. I'd suggest the above if you have no need for that specific file type.
The "scores.rtf" does not change.
well RTF files is handled differently because its not really a pure text file it contains meta-data and tags that controls how text is displayed on the rtf file. please have a time to read to the following sources
http://www.webdev-tuts.com/generate-rtf-file-using-php.html
http://b-l-w.de/phprtf_en.php
http://paggard.com/projects/doc.generator/doc_generator_help.html
if in any case you want a normal text file you can use the code below, don't use fwrite(), please use file_put_contents()
file_put_contents("scores.txt", "\n$name $score");
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.