Search code examples
phparrayswritetofile

PHP write returnable array to file


I need to read and write an array from/to a file.

The file is filled like this:

<?php
    return array(
        'Key' => 'value'
    );
?>

I'm already able to read this file using

$data = include($path . DIRECTORY_SEPARATOR . $file);

How can i write this array back to the file while keeping the structure of '<?php return array(); ?>'?


Solution

  • You can use var_export function:

    file_put_contents(
        $path . DIRECTORY_SEPARATOR . $file, 
        "<?php\nreturn " . var_export($data, true) . "\n?>"
    );