Writing an array to a file in php And getting data

I have an array that looks like this 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 directly 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 it looks like the original. Any idea to solve this?

+6
source share
4 answers

The problem at the moment is that you can only write lines to a file. Therefore, to use file_put_contents , you first need to convert your data to a string.

In this particular use case, there is a function called serialize that converts any type of PHP data into a string (except for resources).

Here is an example of using this.

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

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

Here's how you do it:

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

Here are two ways:

(1) Write the JSON representation of the array object in the file.

 $arr = array( [...] ); file_put_contents( 'data.txt', json_encode( $arr ) ); 

Then later ...

 $data = file_get_contents( 'data.txt' ); $arr = json_decode( $data ); 

(2) Write the serialized representation of the array object to a file.

 $arr = array( [...] ); file_put_contents( 'data.txt', serialize( $arr ) ); 

Then later ...

 $data = file_get_contents( 'data.txt' ); $arr = unserialize( $data ); 

I prefer the JSON method because it does not get corrupted as easily as it is serialized. You can open the data file and make changes to the contents, and it will encode / decode back without big headaches. Serialized data cannot be modified or damaged, or unserialize () will not work.

+4
source

file_put_contents writes a string to a file, not an array. http://php.net/manual/en/function.file-put-contents.php

If you want to write what you see there in this print_r file, you can try the following:

 ob_start(); print_r($myarray); $output = ob_get_clean(); file_put_contents("myfile.txt",$output); 
+3
source

I'm not sure, but maybe something like this. You want to serialize () the array as you write. it will put your array in test.txt

 file_put_contents('test.txt', serialize($array)); 
0
source

All Articles