Ephenodrom
Ephenodrom

Reputation: 1893

PHP parse ini file that includes variables

I try to store different languages in .ini files.

language_en.ini :

HELLO_MSG = "Hello $user ! How are you ?"

php file

$user = "Mike";
$ini_array = parse_ini_file("language_en.ini");
echo $ini_array['HELLO_MSG'];

Output

Hello Mike ! How are you ?

Is it possible to use the $user variable that i set in the ini file or do get just an array with strings if i read in the .ini file with the "parse_ini_file" method.

Upvotes: 0

Views: 1425

Answers (1)

deceze
deceze

Reputation: 522606

You should not be relying on variable interpolation for this anyway. You do not define a variable $user in this file, how can you expect it to be interpolated at any point? Will you define all possible variables before parsing the ini file? That's a mess!

The standard solution to this is sprintf:

$hello = "Hello %s! How are you?";
$message = sprintf($hello, $user);
echo $message;

Further, it seems what you're trying to reinvent here is gettext for localisation. Read this to realise why you want an existing system like gettext, not an ini file.

Upvotes: 3

Related Questions