1

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(); ?>'?

3
  • 1
    Take a look at: file_put_contents() + var_export() Commented Dec 23, 2015 at 10:49
  • Might want to look into xml... Commented Dec 23, 2015 at 10:50
  • XML could but i'm only using it myself so readability within the file is not required. An array in this case has less performance influence so XML has no benefit. When the files would be used by non-technical users i would certainly use XML. Commented Dec 23, 2015 at 11:54

3 Answers 3

4

You can use var_export function:

file_put_contents(
    $path . DIRECTORY_SEPARATOR . $file, 
    "<?php\nreturn " . var_export($data, true) . "\n?>"
);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this will do.
1

better way to store json string in file than again accesss this string to array.

1 Comment

Doesn't work in this case as the file also gets directly imported to a class from a library. In any other case that would ofcouse be an option.
0

You can use serialize() to store an array or object into a string. This code shows how it is done:

<?php

$array = ['Key' => 'value'];

$fh = fopen('array.txt','a+');
fwrite($fh,  serialize($array));
fclose($fh);

$read_array = unserialize(file_get_contents('array.txt'));


var_dump($array,$read_array);
/* 
OUTPUTS 

array(1) {
  ["Key"]=>
  string(5) "value"
}
array(1) {
  ["Key"]=>
  string(5) "value"
}
/*

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.