-6

I have text file that I am generating that looks like this:

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

How could i read through this file and store each line as a key value pair?

ex.

array{
       [ipaddress]=>[host]
       [ipaddress]=>[host]
       [ipaddress]=>[host]
       ..........
     }
gpoo
  • 8,408
  • 3
  • 38
  • 53
arrowill12
  • 1,784
  • 4
  • 29
  • 54

4 Answers4

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

foreach($arr as $line){
  list($ip, $host) = explode(',',$line);
  $ips[$ip]=$host;
}
dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

For a simple solution:

<?php
    $hosts = file('hosts.txt', FILE_SKIP_EMPTY_LINES);
    $results = array();
    foreach ($hosts as $h) {
        $infos = explode(",", $h);
        $results[$infos[0]] = $infos[1];
    }
?>
Louis XIV
  • 2,224
  • 13
  • 16
0

Try the function 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);
Brian Hannay
  • 522
  • 4
  • 19
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>"
?>