This is a small guide on how to save a PHP array to a text file. In this tutorial, I will also show you how to read the file in question.
There are two ways of doing this. One involves encoding the array into a JSON format. The other involves the serialize function, which will basically creates a storable representation of a PHP value (in this case, our array).
Using this method, the following steps are taken:
- The array is encoded into a JSON string using json_encode.
- This JSON string is saved to the text file in question.
- When we want to load the JSON string from our text file, we use the file_get_contents function.
- Finally, we decode the JSON string back into an array using the json_decode function.
A small code example:
<?php //Example array. $array = array('Ireland', 'England', 'Wales', 'Northern Ireland', 'Scotland'); //Encode the array into a JSON string. $encodedString = json_encode($array); //Save the JSON string to a text file. file_put_contents('json_array.txt', $encodedString); //Retrieve the data from our text file. $fileContents = file_get_contents('json_array.txt'); //Convert the JSON string back into an array. $decoded = json_decode($fileContents, true); //The end result. var_dump($decoded);
Personally, I prefer the method above, simply because the file size will be smaller and JSON is an extremely popular format.
Using the serialize method, the following steps are taken:
- The array is serialized into “storable” string. This string represents the structure of our array.
- We save the serialized string to the text file in question.
- As soon as we want to load the serialized string, we use the file_get_contents function.
- We then convert the string back into an array using the unserialize function.
A code example, using the serialize method:
<?php //Example array. $array = array('Ireland', 'England', 'Wales', 'Northern Ireland', 'Scotland'); //Serialize the array. $serialized = serialize($array); //Save the serialized array to a text file. file_put_contents('serialized.txt', $serialized); //Retrieve the serialized string. $fileContents = file_get_contents('serialized.txt'); //Unserialize the string back into an array. $arrayUnserialized = unserialize($fileContents); //End result. var_dump($arrayUnserialized);
Note that these methods can be also used to store arrays in databases and whatnot.