Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanently write variables to a php file with php

I need to be able to permanently change variables in a php file using php.

I am creating a multilanguage site using codeigniter and using the language helper which stores the text in php files in variables in this format: $lang['title'] = "Stuff";

I've been able to access the plain text of the files using fopen() etc and I it seems that I could probably locate the areas I want to edit with with regular expressions and rewrite the file once I've made the changes but it seems a bit hacky.

Is there any easy way to edit these variables permanently using php?

Cheers

like image 537
DonutReply Avatar asked Mar 24 '10 10:03

DonutReply


2 Answers

If it's just an array you're dealing with, you may want to consider var_export. It will print out or return the expression in a format that's valid PHP code.

So if you had language_foo.php which contained a bunch of $lang['title'] = "Stuff"; lines, you could do something along the lines of:

include('language_foo.php');
$lang['title2'] = 'stuff2';
$data = '$lang = ' . var_export($lang, true) . ';';
file_put_contents('language_foo.php', '<?PHP ' . $data . ' ?>');

Alternatively, if you won't want to hand-edit them in the future, you should consider storing the data in a different way (such as in a database, or serialize()'d, etc etc).

like image 107
Chris Avatar answered Oct 27 '22 04:10

Chris


It looks way easier to store data somewhere else (for instance, a database) and write a simple script to generate the *.php files, with this comment on top:

#
# THIS FILE IS AUTOGENERATED - DO NOT EDIT
#
like image 36
Álvaro González Avatar answered Oct 27 '22 04:10

Álvaro González