-6

我正在生成的文本文件如下所示:

ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
ipaddress,host
...

我如何阅读该文件并将每一行存储为键值对?

前任。

array{
       [ipaddress]=>[host]
       [ipaddress]=>[host]
       [ipaddress]=>[host]
       ..........
     }
4

4 回答 4

1
$arr = file('myfile.txt');
$ips = array();

foreach($arr as $line){
  list($ip, $host) = explode(',',$line);
  $ips[$ip]=$host;
}
于 2013-01-16T16:50:03.297 回答
0

对于一个简单的解决方案:

<?php
    $hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
    $results = array();
    foreach ($hosts as $h) {
        $infos = explode(",", $h);
        $results[$infos[0]] = $infos[1];
    }
?>
于 2013-01-16T16:51:05.733 回答
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);
于 2013-01-16T16:52:57.717 回答
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>"
?>
于 2013-01-16T16:59:07.917 回答