I have An array which looks like following after using print_r
Array ( [0] => Array ( [0] => piklu [name] => piklu ) [1] => Array ( [0] => arindam [name] => arindam ) [2] => Array ( [0] => shyamal [name] => shyamal ) [3] => Array ( [0] => arko [name] => arko ) [4] => Array ( [0] => pamela [name] => pamela ) [5] => Array ( [0] => dodo [name] => dodo ) [6] => Array ( [0] => tanmoy [name] => tanmoy ) [7] => Array ( [0] => jitu [name] => jitu ) [8] => Array ( [0] => ajgar [name] => ajgar ) )
Now I want to write this array direct to a file, I use the file_put_contents
method, but I don’t know how to get the data from the file exactly how they looks like original. Any idea to solve this?
Advertisement
Answer
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);