I have a file without any format called .env
.
All the values are stored like this: X=Y
My supervisor told me to load this data into my PHP script, I need the values as array. He said I can do it because the file is build like an ini file. But there are no sections.
I tried it like this:
$ini_array = parse_ini_file("../../.env"); // Output: false
$data = include("../../.env"); // Output: 1 -> prints the content of the file into the document
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
APP_DEBUG=true
APP_URL=http://api-konfigurator.local
JWT_SECRET=5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=x
DB_USERNAME=y
DB_PASSWORD=z
It should be fairly straightforward to parse a file in the format mentioned but complicated slightly by some lines potentially including multiple =
signs, such as for APP_KEY
That said, perhaps the following might help.
$filepath='c:/temp/fakeini.txt';
$data=array();
$lines=file( $filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
foreach( $lines as $index => $line ){
if( !empty( $line ) ){
$count=substr_count( $line, '=' );
if( $count > 1 ){
$pos=strpos($line,'=');
$param=substr($line,0,$pos);
$value=substr($line,$pos+1);
}else{
list( $param, $value )=explode( '=', trim( $line ) );
}
$data[ $param ]=$value;
}
}
which yields an array like this:
Array
(
[APP_NAME] => Laravel
[APP_ENV] => local
[APP_KEY] => base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
[APP_DEBUG] => true
[APP_URL] => http://api-konfigurator.local
[JWT_SECRET] => 5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3
[LOG_CHANNEL] => stack
[DB_CONNECTION] => mysql
[DB_HOST] => localhost
[DB_PORT] => 3306
[DB_DATABASE] => x
[DB_USERNAME] => y
[DB_PASSWORD] => z
)