Demo

ソースコード


<?php 

$envs = getEnvSimple('.env');
echo '<pre>';
var_dump($envs);
echo '</pre>';

function getEnvSimple($env_fn) {
    
    // 引数のiniファイル名が空、もしくは存在しなければ、なら、nullを返して終了
    if (! $env_fn)  return null;
    
    
    $str = null;
    $env_fn=mb_convert_encoding($env_fn,'SJIS','UTF-8');
    if (!is_file($env_fn)){
        return null;
    }
    
    if ($fp = fopen ( $env_fn, "r" )) {
        $data = array ();
        while ( false !== ($line = fgets ( $fp )) ) {
            $str .= mb_convert_encoding ( $line, 'utf-8', 'utf-8,sjis,euc_jp,jis' );
        }
    }
    fclose ( $fp );
    
    $ary = preg_split( "/¥R/", $str );
    
    $envs = [];
    foreach($ary as $line_str){
        $line_str = trim($line_str);
        if(empty($line_str)) continue;
        
        $ary2 = preg_split("/=/", $line_str);
        if(count($ary2) < 2) continue;
        
        $key = trim($ary2[0]);
        if(empty($key)) continue;
        
        $envs[$key] = trim($ary2[1]);
        
    }
    
    return $envs;
}

?>

出力

array(11) {
  ["ANIMAL_NAME"]=>
  string(18) "おキャット様"
  ["APP_NAME"]=>
  string(7) "Example"
  ["APP_ENV"]=>
  string(5) "local"
  ["APP_KEY"]=>
  string(50) "base64:gwTmSBhSHtDmqDNg9ZaHSpYsNgGWmkZihBtxVqZklmI"
  ["APP_DEBUG"]=>
  string(4) "true"
  ["APP_URL"]=>
  string(16) "http://localhost"
  ["LOG_CHANNEL"]=>
  string(5) "stack"
  ["LOG_DEPRECATIONS_CHANNEL"]=>
  string(4) "null"
  ["LOG_LEVEL"]=>
  string(5) "debug"
  ["DB_CONNECTION"]=>
  string(5) "mysql"
  ["DB_HOST"]=>
  string(9) "localhost"
}