Storing some Key/Values in a text file?

Hi,

I am looking into creating a saving some key/value stuff in a text file, maybe I need JSON?, then, I would like to retrieve the information to use later on.

Basically what I want to do is have some options like so:

  • Event Time = 17:30
  • Amount of Guests = 12
  • Guests = Ann/26yr/Doctor, Barry/55yr/Accountant, Keith/32yr/Web Designer

Note, Guests are multidimensional and are dynamic, meaning there could be just 1 guest or or 100+.

Any idea on how to approach this problem?

You can use parse_ini_file to parse your config.

I would definitely use something like JSON for this; figuring out encoding/decoding scheme can be a real pain* so I’d use something that already exists. That way you can store the whole thing in an array


array(
  'event_time' => '17:30',
  'guests' => array(
    array(
      'name' => 'Ann',
      'age' => 26,
      'occupation' => 'Doctor',
    ),
    array(
      'name' => 'Barry',
      'age' => 55,
      'occupation' => 'Accountant',
    ),
    array(
      'name' => 'Keith',
      'age' => 32,
      'occupation' => 'Web Designer',
    )
  )
);

run it through json_encode, write it to a file and you’re done. Please note that I removed the ‘number of guests field’; as a general rule you don’t store meta data that can also be found out otherwise (in this case you can just count the number of elements in the array).

If you’re expecting a lot of hits on this you may be better off using a database, like MySQL, or a key/value store, like MongoCB, couchDB, cassandra, etc.

  • Suppose somebody worked at a company called east/west, how would you know the / is part of the name of the company? You could replace it by something like a dash, but then what do you do when you find a dash when you decode? Replace it with a slash, or was it supposed to be a dash? etc, etc, etc, ad nauseam.

$a = array(
  'event_time' => '17:30',
  'guests' => array(
    array(
      'name' => 'Ann',
      'age' => 26,
      'occupation' => 'Doctor',
    ),
    array(
      'name' => 'Barry',
      'age' => 55,
      'occupation' => 'Accountant',
    ),
    array(
      'name' => 'Keith',
      'age' => 32,
      'occupation' => 'Web Designer',
    )
  )
);

file_put_contents( 'textfile.txt', var_export( $a, true ) );

/// Now read...

$b = include 'textfile.txt';

var_dump( $a, $b );