解析一个类似CVS的文件,并将其存储为字典
问题描述:
我有我产生,看起来像这样的文本文件:解析一个类似CVS的文件,并将其存储为字典
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...
我怎么会通过这个文件中读取并存储每个线作为键值对?
ex。
array{
[ipaddress]=>[host]
[ipaddress]=>[host]
[ipaddress]=>[host]
..........
}
答
$arr = file('myfile.txt');
$ips = array();
foreach($arr as $line){
list($ip, $host) = explode(',',$line);
$ips[$ip]=$host;
}
答
对于一个简单的解决方案:
<?php
$hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
$results = array();
foreach ($hosts as $h) {
$infos = explode(",", $h);
$results[$infos[0]] = $infos[1];
}
?>
答
尝试的功能explode。
//open a file handler
$file = file("path_to_your_file.txt");
//init an array for keys and values
$keys= array();
$values = array();
//loop through the file
foreach($file as $line){
//explode the line into an array
$lineArray = explode(",",$line);
//save some keys and values for this line
$keys[] = $lineArray[0];
$values[] = $lineArray[1];
}
//combine the keys and values
$answer = array_combine($keys, $values);
答
<?php
$handle = @fopen("ip-hosts.txt", "r");
$result = array();
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$t = explode(',', $buffer);
$result[$t[0]] = $t[1];
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
// debug:
echo "<pre>";
print_r($result);
echo "</pre>"
?>
[你已经尝试什么?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) –
正则表达式。 – argentage
@airza,为什么?我不会在这里使用正则表达式,它是简单的字符串分割。 –