我生成的文本文件如下所示:
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...
我如何阅读此文件并将每一行存储为键值对?
离。
array{
[ipaddress]=>[host]
[ipaddress]=>[host]
[ipaddress]=>[host]
..........
}
答案 0 :(得分:1)
$arr = file('myfile.txt');
$ips = array();
foreach($arr as $line){
list($ip, $host) = explode(',',$line);
$ips[$ip]=$host;
}
答案 1 :(得分:0)
一个简单的解决方案:
<?php
$hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
$results = array();
foreach ($hosts as $h) {
$infos = explode(",", $h);
$results[$infos[0]] = $infos[1];
}
?>
答案 2 :(得分:0)
尝试使用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);
答案 3 :(得分:0)
<?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>"
?>