8

I want to avoid writing to DB and use constants/array for lang files etc.

i.e:

$lang = array (
  'hello' => 'hello world!'
);

and be able to edit it from the back office. (then instead of fetching it from the poor db, i would just use $lang['hello']..).

what are you suggesting for the best and efficient way to pull it of?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
WEBProject
  • 1,337
  • 5
  • 16
  • 33

4 Answers4

19

the most efficient way i found looks like this:

build up your array in php somehow and export it into a file using var_export()

file_put_contents( '/some/file/data.php', '<?php return '.var_export( $data_array, true ).";\n" );

then later, wherever you need this data pull it like this

$data = include '/some/file/data.php';
Jan Prieser
  • 1,529
  • 9
  • 15
  • i would prefer serialize over var_export. An attacker could put malicious code into the .php containing the variables and it gets executed. – MarcDefiant Sep 21 '12 at 13:21
  • @Mogria Well, if an attacker has access to the language files, he presumably could inject that code into any other file as well... :) – deceze Sep 21 '12 at 13:24
  • @deceze not necessarily, the file you write these variables to needs to be writeable for php. The other files only need to be readable. – MarcDefiant Sep 21 '12 at 13:26
  • 2
    you don't need to write the file from a script which is accessible from the outside. the most efficient and fast way to read data arrays is this include. serialize/unserialize needs more memory and cpu and even bytes in the file. – Jan Prieser Sep 21 '12 at 13:32
12

Definitely JSON

To save it :

file_put_contents("my_array.json", json_encode($array));

To get it back :

$array = json_decode(file_get_contents("my_array.json"));

As simple as that !

Olivier Kaisin
  • 519
  • 3
  • 12
  • 3
    Please note that if you want to save disk space (when using very large arrays ie) you can always store it in files as binary data – Olivier Kaisin Sep 21 '12 at 13:26
6

Well if you insist to put the data into files, you might consider php functions serialize() and unserialize() and then put the data into files using file_put_contents.

Example:

<?php
$somearray = array( 'fruit' => array('pear', 'apple', 'sony') );
file_put_contents('somearray.dat', serialize( $somearray ) );
$loaded = unserialize( file_get_contents('somearray.dat') );

print_r($loaded);
?>
Khôi
  • 2,133
  • 11
  • 10
3

You can try json_encode() and json_decode().

$save = json_encode($array);

write contents of $save to file

To load lang use:

$lang = file_get_contents('langfile');
$lang = json_decode($lang, true);
Piotr
  • 335
  • 2
  • 6