I have some JavaScript code that sends an array to a php page and I want to save it into a text file. In each process of the JavaScript file there could be multiple arrays - currently 14 arrays.
I am using some code that saves the data using serialize but I have one long string and I do not know how to retrieve it as individual arrays.
Code to save to the file
$params = $_POST["params"]; // This is an array
$string_data = serialize($params);
file_put_contents('face.txt', $string_data, FILE_APPEND | LOCK_EX);
Please can somebody point me in the right direction to get the individual arrays to use in the next step. I will need to use all the arrays in one process on the next page.
You’re better off using json_encode() because they’ll be JavaScript ready (and human readable).
It looks like you’re appending data though, so you’ll need to do a little processing. Here’s how I would do it: Saving:
$params = $_POST["params"]; // This is an array
$string_data = json_encode($params) . ",\n"; # Notice the comma and newline character
file_put_contents('face.txt', $string_data, FILE_APPEND | LOCK_EX);
Reading:
$string_data = file_get_contents('face.txt', true); # Grab the data
$string_data = rtrim(trim($string_data), ','); # Remove that last white-space and comma to make it JSON ready
# $string_data = '[' . $string_data . ']'; # You might need this to make it a valid JSON object, I forget
$string_data = json_decode($string_data); # Convert it back into a PHP Object/Array
At this point, $string_data will actually be an ARRAY/OBJECT, so you can just grab the last values with array_pop() or array_slice(). If the file is ginormous you can make use of fseek().
An analytics tool I built writes to files similarly to exactly how you describe: https://ozramos.com/db/metrics/metrics.txt. I use newlines too as that lets me grab the last lines of the file without opening the entire thing into RAM.
Yes I am adding the arrays to the text file each time the Jquery code posts it to the php page. I was surprised it worked as the Jquery sends the data quickly and I thought some of the data would get lost while other data was still being written.
Thanks for the help, your code worked perfectly and yes I did need the line you had commented out.