我正在生成的文本文件如下所示:
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...
我如何阅读该文件并将每一行存储为键值对?
前任。
array{
[ipaddress]=>[host]
[ipaddress]=>[host]
[ipaddress]=>[host]
..........
}
我正在生成的文本文件如下所示:
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...
我如何阅读该文件并将每一行存储为键值对?
前任。
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>"
?>