phparraysfopenfputs

create PHP array using fopen with append


I am having trouble figuring out how to write to a file using fopen "a" append mode.

the file itself is a simple PHP array:

$array = array(
  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",
);   

simple enough. So using fopen with the 2nd arg set to "a" should allow me to append the file using fputs.... the problem is the opening and closing lines, ie $array = array( and );

so now the file should look like this:

  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",

how would I rebuild this data into a working PHP array assuming it is just a txt file with a list of entries without the opening and closing lines? Sorry if this is not clear, its a little complicated. No I am not going to store these values in a DB, I need the speed advantage by holding these particular values in a file array.

So the questions really is how would i go about constructing the usable PHP array from a txt file with a line by line list like this?

To clarify:

how do i pull in a txt file with lines like this:

  "entry1"   => "blah blah",
  "entry2"   => "forbarbaz",

and have a workable $php_array()????


Solution

  • Try this.

    File format (at the beginning of work with it):

    <?php
    $array = array();
    

    Now it's correct php-file.

    Then simply add new rows like as follows:

    $f = fopen('myarray.php', 'a');
    fputs($f, PHP_EOL.'$array["entry1"] = "value1";');
    fclose($f);
    

    And use it by simply include('myarray.php');