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

时间:2014-10-27 13:07:26

标签: php arrays file

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

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

我希望将=字符左侧的单词作为键,将右侧的单词作为对应值。

我的结果应该是

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

2 个答案:

答案 0 :(得分:5)

您可以使用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
)

答案 1 :(得分:-2)

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

//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);