Question

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

Was it helpful?

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

OTHER TIPS

Why not json_encode the array when you store it in the file and then json_decode the JSON into an array when you extract it from the file?

json_encode
json_decode

Untested. Try this:

$data = file_get_contents('./data.txt', true);
$array = eval("array(".$data.")");

FYI, shiplu.mokadd.im's solution is the easiest.

Maybe you're looking for the fseek function: http://se.php.net/fseek

When opening a file in r+ mode, the file pointer is at the beginning of the file. Sounds like you want to place it at the end of the file minus a few bytes, then write your new data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top