user2632667 user2632667 - 11 months ago 56
PHP Question

How to save multidimensional array to a flat text file - PHP

I have a multidimensional array, currently it's only printing the array on the page. I want to be able to save it in a flat text file storing the selected checkbox information when the user submits it. There are 6 days in total.

Answer Source

I'd simply do this:

    if ($_POST)
    {//always check, to avoid noticed
        file_put_contents('theFilenameToWriteTo.json', json_encode($_POST));

The benefit of json_encode is that it's more or less standard. All languages that I know of can parse this format. If you're using node.js, it can read the data, Java? JSON-java is there for you. Python? import json, hell, even C++ libs are easy to find.
To reuse that data in PHP:

$oldPost = json_decode(file_get_contents('theFileNameToRead.json'));
//$oldPost will be an instance of stdClass (an object)
//to get an assoc-array:
$oldPostArray = json_decode(file_get_contents('sameFile.json'), true);

There are other options to: serialize and write, followed by unserialize on read.
If you want that array to be copy-pastable into existing PHP code, use var_export

file_put_contents('theArray.txt', var_export($_POST, true));

If you open the file then, it'll contain an array as though it were written by hand:

array (
  0 => 1,
  1 => 2,
  2 => 
  array (
    0 => 'a',
    1 => 'b',
    2 => 'c',

As Carlos Campderrós pointed out, you can even include strings generated by var_export. It's important to note that var_export doesn't handle circular references, though, but seeing as you're using a $_POST array, that's not an issue here
To recap, a list of useful functions: