coffeemonitor coffeemonitor - 22 days ago 7
PHP Question

PHP Array saved to Text file

I've saved a response from an outside server to a text file, so I don't need to keep running connection requests. Instead, perhaps I can use the text file for my manipulation purposes, until I'm read for re-connecting again. (also, my connection requests are limited to this outside server)

Here is what I've saved to a text file:

records.txt

Array
(
[0] => stdClass Object
(
[id] => 552
[date_created] => 2012-02-23 10:30:56
[date_modified] => 2012-03-09 18:55:26
[date_deleted] => 2012-03-09 18:55:26
[first_name] => Test
[middle_name] =>
[last_name] => Test
[home_phone] => (123) 123-1234
[email] => someemail@somedomain.com
)
[1] => stdClass Object
(
[id] => 553
[date_created] => 2012-02-23 10:30:56
[date_modified] => 2012-03-09 18:55:26
[date_deleted] => 2012-03-09 18:55:26
[first_name] => Test
[middle_name] =>
[last_name] => Test
[home_phone] => (325) 558-1234
[email] => someemail@somedomain.com
)
)


There's actually more in the Array, but I'm sure 2 are fine.

Since this is a text file, and I want to pretend this is the actual outside server (sending me the same info), how do I make it a real array again?

I know I need to open the file first:

<?php
$fp = fopen('records.txt', "r"); // open the file
$theData = fread($fh, filesize('records.txt'));
fclose($fh);
echo $theData;
?>


So far
$theData
is a string value. Is there a way to convert it back to the Array it originally came in as?

Answer

Better serialize and save to file, then unserialize back to array.

// serialize your input array (say $array)
$serializedData = serialize($array);

// save serialized data in a text file
file_put_contents('your_file_name.txt', $serializedData);

// at a later point, you can convert it back to array like:
$recoveredData = file_get_contents('your_file_name.txt');

// unserializing to get actual array
$recoveredArray = unserialize($recoveredData);

// you can print your array like
print_r($recoveredArray);