I have a php file which contains just some variables and their values something like this:
<?php
$first = "value1";
$second = 'value2';
$third = 'value3';
$fourh = 'value4';
?>
How could I read this file dynamically and save it in an array? I could do this by parsing the file but is there a php function which does that?
What would be the best way to do this?
PHP has a function: get_defined_vars that might be useful.
You could leverage this function like so:
$currentVars = get_defined_vars();
include 'variables.php';
$fileVars = array_diff(get_defined_vars(), $currentVars);
$fileVars
should be an array containing the variable binding from that file.
As you say in your comment:
This php file is my config.inc.php, and I want to show this to my user- who is an admin of my web application- over an administration panel
So you need a better approach, this is going to be painful on the long run.
Rewrite your file as the following:
[values]
first = "value1"
second = "value2"
third = "value3"
fourh = "value4"
Save it however you want, but i suggest an ".ini" extension (it's not necessary, even ".foo" will be ok)
in your PHP script, call $ini_array = parse_ini_file("sample.ini");
and voila, $ini_array
contains what you need.
The manual page for parse_ini_file has more examples and istructions. Take a look: http://php.net/manual/en/function.parse-ini-file.php