我有一个看起来像这样的文本文件:
NAME=ARTHUR
LASTNAME=McConnell
AGE=43
我想用它来做一个这样的数组:
Array (
[NAME] => ARTHUR
[LASTNAME] => McConnell
[AGE] => 43
)
非常感谢所有帮助。
答案 0 :(得分:1)
如果您的文件格式具有完全相同的语法,则可以使用parse_ini_file()
。它不关心文件扩展名,因此您也可以在.txt
文件上应用它,只要格式正确。
<强>的test.txt 强>
NAME=ARTHUR
LASTNAME=McConnell
AGE=43
<强> parser.php 强>
<?php
$data = parse_ini_file('test.txt');
var_dump($data);
答案 1 :(得分:1)
$filename = 'info.txt';
//Read the file into a line-by-line array
$contents = file($filename);
//Loop through each line
foreach($contents as $line) {
//Split by the = sign
$temp_array = explode('=', $line);
//Rebuild new array
$new_array[$temp_array[0]] = $temp_array[1];
}
//Print out the array at the end for testing
var_dump($new_array);
答案 2 :(得分:0)
您可以使用parse_ini_file
$data = parse_ini_file('myFile.txt');
或两次使用explode
// first in end of lines
$data = explode(PHP_EOL, file_get_contents('myFile.txt'));
// and after, make a loop on the resulting array and creating a new array
$arr = array();
foreach ($data as $row) {
$line = explode("=", $row);
$arr[$line[0]] = $line[1];
}
答案 3 :(得分:0)
认为我已经在变量
中给出了它$variable = "NAME=ARTHUR
LASTNAME=McConnell
AGE=43"
//instead of this you can read the whole file
$lines = explode(PHP_EOL, $variable);