Save and retreave multiple arrays to a text file or a clever alternative!

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);

Example arrays

    [0] => face_1
    [1] => 333
    [2] => 62
    [3] => 33
    [4] => 33

    [0] => face_2
    [1] => 177
    [2] => 92
    [3] => 29
    [4] => 29

Example of file contents - 2 arrays here and along with the other 12 they are all on one line ( strange they display as two lines here! )


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:

$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);


$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: 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.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.