Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write and extract array

Tags:

arrays

php

Variable $total is an array().

print_r($total) gives:

Array (
    [01] => Array ( [title] => text [date] => date )
    [02] => Array ( [title] => text [date] => date )
    [03] => Array ( [title] => text [date] => date )
)

How to write this array to file.txt?

And how to call created file later, so I can work with array inside it? Like:

$extracred_array = file.txt;
echo $extracred_array[1][title];

Thanks.

like image 948
James Avatar asked May 09 '26 06:05

James


1 Answers

You need to serialize it with serialize function like this:

$serialize_array = serialize($array);

Now you can save the $serialize_array in your file. To read it back and convert to array again, use the unserialize function.

Update:

// write array data to file
file_put_contents('file.txt', serialize($your_array));    

To read the file back:

// read array back from file
$contents = file_get_contents('file.txt');

// show the array
print_r(unserialize($contents));
like image 174
Sarfraz Avatar answered May 10 '26 19:05

Sarfraz