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.
3 Answers
I'd simply do this:
<?php
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:
1 Comment
var_export'ed code with an include or require :DYou could use the
print_r($multiArray,true)
The true means we want to capture the output and not print.
Array (PHP 5.4 )
$multiArray = [
0 => [ 'a' => 'b'],
1 => [ 'c' => 'd',
'e' => [
'f' => 'g',
'h' => 'i'
]
],
];
PHP
$file = 'array.txt';
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, print_r($multiArray,true));
fclose($fh);
Or you could use the serialize() and unserialize() if you want to use the array later
fwrite($fh, serialize($multiArray) );
serializeitjson_encodeit, so you can easily read it in other languages, toofile_put_contents('path/to/your/file', json_encode($_POST));