How to Store an Array in a File to Access as an Array Later with PHP

How do I store an array in a file to access as an array later with PHP?

The best way to do this is JSON serializing. It is human readable and you'll get better performance (file is smaller and faster to load/save). The code is very easy. Just two functions

  • json_encode
  • json_decode

Example code:

$arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
file_put_contents("array.json",json_encode($arr1));
# array.json => {"a":1,"b":2,"c":3,"d":4,"e":5}
$arr2 = json_decode(file_get_contents('array.json'), true);
$arr1 === $arr2 # => true

You can write your own store_array and restore_array functions easily with this example.

For speed comparison see benchmark originally from Preferred method to store PHP arrays (json_encode vs serialize).

Save array to PHP file

The function you're looking for is var_export

You would use it like this

file_put_contents($filename, '<?php $arr = ' . var_export($arr, true) . ';');

DEMO

Saving array to php file

I just cobbled this together for the purposes of testing - because I was curious (I didn't bother with XML parsing as that's even slower than json_encode()):

<?php

header('Content-Type: text/plain;charset=utf-8');
set_time_limit(120);

//define variables
$iLoopCount = 10000;
$aTheArray = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
$fStartTime = microtime(true);

//function to convert an array into a string used to create a PHP include file
function convertArrayToInclude(array $aIn) {
$sOut = 'array(';
foreach($aIn as $key => $value) {
$formattedKey = is_string($key) ? "'{$key}'" : $key;
$formattedValue = is_string($value) ? "'{$value}'" : $value;

$sOut .= "{$formattedKey} => {$formattedValue},";
}
$sOut = substr($sOut, 0, -1) . ');';

return $sOut;
}

//test serialize
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("serialize.txt", serialize($aTheArray), LOCK_EX);
$aReadArray1 = unserialize(file_get_contents("serialize.txt"));
}

$fStopTime1 = microtime(true);
echo "serialize execution time ({$iLoopCount} iterations) : " . ($fStopTime1 - $fStartTime) . "s\n\n";

//test json_encode
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("json_encode.txt", json_encode($aTheArray), LOCK_EX);
$aReadArray2 = json_decode(file_get_contents("serialize.txt"));
}

$fStopTime2 = microtime(true);
echo "json_encode execution time ({$iLoopCount} iterations) : " . ($fStopTime2 - $fStopTime1) . "s\n\n";

//test native using fixed data
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("include.php",
'<?php $aReadArray3 = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); ?>'
, LOCK_EX);

include 'include.php';
}

$fStopTime3 = microtime(true);
echo "native include execution time with fixed data ({$iLoopCount} iterations) : " . ($fStopTime3 - $fStopTime2) . "s\n\n";

//test native using dynamic data
for($i = 0; $i < $iLoopCount; $i++) {
file_put_contents("include2.php",
'<?php $aReadArray4 = ' . convertArrayToInclude($aTheArray) . ' ?>'
, LOCK_EX);

include 'include2.php';
}

$fStopTime4 = microtime(true);
echo "native include execution time with dynamic data ({$iLoopCount} iterations) : " . ($fStopTime4 - $fStopTime3) . "s\n\n";

?>

Hit refresh a few times to see reasonably consistent results, but this is sort of what you're looking at:

  • serialize execution time (10000 iterations) : 4.6746249198914s

  • json_encode execution time (10000 iterations) : 5.132187128067s

  • native include execution time with fixed data (10000 iterations) : 4.863872051239s

  • native include execution time with dynamic data (10000 iterations) : 5.5474679470062s

So, in short : if you can build your php include as a string (native fixed data) then writing and including that file repeatedly is potentially the quickest method (see notes). However, if you want to include some sanity checks or convert an array to a string that can be used within that include (native dynamic data) you're into a whole world of hurt - you've got function and processing overheads as well as any/all security vulnerabilities introduced by your 'roll your own' solution. It's the slowest and worst way to go.

In very short : PHP has functions for storing variables as text ( serialize() ) and retrieving them ( unserialize() ) ... just use them instead of trying to reinvent the wheel.


Note: the difference in execution time between using serialize() and fixed native data wobbled with each refresh, sometimes one was faster, sometimes the other - essentially it made very little difference to the actual speed.

Writing Array to File in php And getting the data

Your problem at the moment is basically that you're only able to write strings into a file. So in order to use file_put_contents you first need to convert your data to a string.

For this specific use case there is a function called serialize which converts any PHP data type into a string (except resources).

Here an example how to use this.

$string_data = serialize($array);
file_put_contents("your-file.txt", $string_data);

You probably also want to extract your data later on. Simply use unserialize to convert the string data from the file back to an array.

This is how you do it:

$string_data = file_get_contents("your-file.txt");
$array = unserialize($string_data);

Reading and writing arrays in PHP?

As suggested by Mark Baker, you need to serialize the data in order to save it to the file. Later you can read it and deserialize it back to an array. Here is how:

<?php

// DISPLAY ARRAY BEFORE SAVING IT.
$old_array = array( "Page1" => 10,
"Page2" => 3,
);
echo "OLD ARRAY" .
"<br/><br/>";
print_r( $old_array );

// WRITE ARRAY TO FILE.
$old_data = serialize( $old_array );
file_put_contents( "my_file.txt",$old_data );

// READ ARRAY FROM FILE.
$new_data = file_get_contents( "my_file.txt" );
$new_array = unserialize( $new_data );

// DISPLAY ARRAY TO CHECK IF IT'S OK.
echo "<br/><br/>" .
"NEW ARRAY" .
"<br/><br/>";
print_r( $new_array );

?>

This is what you should see on screen :

OLD ARRAY

Array ( [Page1] => 10 [Page2] => 3 )

NEW ARRAY

Array ( [Page1] => 10 [Page2] => 3 )

And, if you open "my_file.txt" you will see this:

a:2:{s:5:"Page1";i:10;s:5:"Page2";i:3;}

Print array to a file

Either var_export or set print_r to return the output instead of printing it.

Example from PHP manual

$b = array (
'm' => 'monkey',
'foo' => 'bar',
'x' => array ('x', 'y', 'z'));

$results = print_r($b, true); // $results now contains output from print_r

You can then save $results with file_put_contents. Or return it directly when writing to file:

file_put_contents('filename.txt', print_r($b, true));


Related Topics



Leave a reply



Submit