You could serialize
the array before writing it as text to a file. Then, you can read the data back out of the file, unserialize
will turn it back into an array.
http://php.net/manual/en/function.serialize.php
EDIT Describing the process of using serialize/unserialize:
So you have an array:
$arr = array(
'one'=>array(
'subdata1',
'subdata2'
),
'two'='12345'
);
When I call serialize
on that array, I get a string:
$string = serialize($arr);
echo $string;
OUTPUT: a:2:{s:3:"one";a:2:{i:0;s:8:"subdata1";i:1;s:8:"subdata2";}s:3:"two";s:5:"12345";}
So I want to write that data into a file:
$fn= "serialtest.txt";
$fh = fopen($fn, 'w');
fwrite($fh, $string);
fclose($fh);
Later, I want to use that array. So, I'll read the file, then unserialize:
$str = file_get_contents('serialtest.txt');
$arr = unserialize($str);
print_r($arr);
OUTPUT: Array ( [one] => Array ( [0] => subdata1 [1] => subdata2 ) [two] => 12345 )
Hope that helps!
EDIT 2 Nesting demo
To store more arrays into this file over time, you have to create a parent array. This array is a container for all the data, so when you want to add another array, you have to unpack the parent, and add your new data to that, then repack the whole thing.
First, get your container set up:
// Do this the first time, just to create the parent container
$parent = array();
$string = serialize($arr);
$fn= "logdata.log";
$fh = fopen($fn, 'w');
fwrite($fh, $string);
fclose($fh);
Now, from there forward, when you want to add a new array, first you have to get the whole package out and unserialize it:
// get out the parent container
$parent = unserialize(file_get_contents('logdata.log'));
// now add your new data
$parent[] = array(
'this'=>'is',
'a'=>'new',
'array'=>'for',
'the'=>'log'
);
// now pack it up again
$fh = fopen('logdata.log', 'w');
fwrite($fh, serialize($parent));
fclose($fh);