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] => [email protected]
)
[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] => [email protected]
)
)
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?
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);
You shouldn't have saved it in print_r
format then.
Use either:
serialize()
json_encode()
var_export()
That makes it simple to decode the file back into an array.
Albeit there is a print_r decoder. But that should be the last resort, only if you cannot affect the input data (which you can!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With