如何在PHP中从文本文件创建键值数组


How to create a key-value array from a text file in PHP?

我正在为一个多语言网站创建一个词典。我有一个文本文件,其中包含一些KEY = "VALUE"格式的数据。

STACKOVERFLOW="Stackoverflow"
ASKING_A_QUESTION="Asking a Question"
...

我想得到=字符左侧的单词作为键,右侧的单词作为相应的值。

我的结果应该像

echo $resultArray['STACKOVERFLOW']; // Stackoverflow

您可以使用parse_ini_file():

; file:
[second_section]
path = "/usr/local/bin"
URL = "http://www.example.com/~username"

代码

// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

输出

Array
(
    [path] => /usr/local/bin
    [URL] => http://www.example.com/~username
)

查看我的评论。(未测试代码)

//Get the content of your file into an array by rows
$content = file('yourfile.txt');
//Init an array
$array = array();
//Set the number of current row
$i = 1;
//Looping on each rows
foreach ($content as $row) {
    //Explode the row by = sign
    $tmp = explode("=", $row);
    //If we have exactly 2 pieces
    if (count($tmp) === 2) {
        //Trim the white space of key
        $key = trim($array[0]);
        //Trim the white spaces of value
        $value = trim($array[1]);
        //Add the value to the given key! Warning. If you have more then one
        //value with the same key, it will be overwritten. You can set 
        //a condition here with an array_key_exists($key, $array);
        $array[$key] = $value;
    } else {
        //If there are no or more then one equaltion sign in the row
        die('Not found equalation sign or there are more than one sign in row: ' . $i);
    }
    //Incrase the line number
    $i++;
}
//Your result
var_dump($array);