This is a tutorial on how to save a PHP array to a text file.
In this tutorial, we 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).
JSON.
To save a PHP array to a text file using the JSON functions, we can take the following steps.
- Encode the array into a JSON string using json_encode.
- Save the JSON string to the text file in question.
- If we want to load the JSON string from our text file, then we can use the file_get_contents function.
- Finally, we can decode the JSON string back into an array by using the json_decode function.
Take a look at the following example.
//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 a far more portable format.
Serialized Data
Using the serialize method, we can take the following steps.
- 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 you can also use this method to store PHP arrays in databases and whatnot.