1

I've outputted my array to file using the print_r($myArray, true) method, but am having trouble re-importing it as an array.

I keep returning a string with the array, not the array itself. I've tried a few different combinations including print_r and serialize, but can't seem to get it right. What am I missing?

Here's what I have:

$myArray = print_r(file_get_contents($logFile), true);

for reference the log file content looks like so:

Array
(
    [0] => Array
        (
            [0] => blah
            [1] => blah
        )
...

Thanks


EDIT: Solution - Here is what I came up with:

I changed the file contents to include php tags and declared the array there using var_export instead of print_r.

Here is what I used as my content string when writing to file:

<?php $myArray = '.var_export($myArray, true).'; ?'.'>

From there it was a simple include to get the array back.

John
  • 11,985
  • 3
  • 45
  • 60
  • 1
    Possible duplicate of http://stackoverflow.com/questions/7025909/create-array-printed-with-print-r The selected answer contains quite a nice function that could help you out! – Adi Bradfield Jun 14 '13 at 15:50
  • @AdiBradfield thanks for that. I found another workaround that I think is a little cleaner. – John Jun 14 '13 at 16:26
  • Would you mind posting it? I'm intrigued! – Adi Bradfield Jun 14 '13 at 16:35
  • 1
    @AdiBradfield I basically just did `fwrite($logFile, '')` and created a .php file with the array declared. I then just included it in the original. – John Jun 14 '13 at 16:52
  • Hmm that is a lot cleaner and no more hacky than that function! Good thinking – Adi Bradfield Jun 14 '13 at 16:55

1 Answers1

0

You should just store the array as ... an array, like so:

file_put_contents('myfile.txt', '<?php return ' . var_export($array, true) . '; ?>');

Then, to read:

$array = include 'myfile.txt';

See also: var_export()

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309