Skip to content
Advertisement

Text File to Array

I am trying to put my text file into an array..

my text file content is like this:

TP-Link|192.168.1.247|CHANNEL 02|warehouse
Ruckus|192.168.1.248|CHANNEL 03|entrance

anyone can help me to make the output looks like this:

$servers = array(
    array(
        'name' => 'TP-Link',
        'ip' => '192.168.1.247',
        'channel' => 'CHANNEL 02',
        'location' => 'warehouse',
    ),  
    array(
        'name' => 'Ruckus',
        'ip' => '192.168.1.248',
        'channel' => 'CHANNEL 03',
        'location' => 'entrance',
    ),
);

thanks in advance..

this is my code:-

$file="config/data.txt";

$fopen = fopen($file, r);

$fread = fread($fopen,filesize($file));

fclose($fopen);

$remove = "n";

$split = explode($remove, $fread);

$servers[] = null;
$tab = "|";

foreach ($split as $string)
{
    $row = explode($tab, $string);
    array_push($servers,$row);
}

the problem is it outputs a multidimensional without array names..

and i am not familiar in multidimensional array..

Advertisement

Answer

You can do something like this. Check out explode and fgets

<?php

$servers_array = array();
$handle = @fopen("inputfile.txt", "r");

if ($handle) {
    while (($buffer = fgets($handle)) !== false) {
        $line = explode("|", $buffer);
        
        $servers_array[] = array(
            "name" => $line[0],
            "ip" => $line[1],
            "channel" => $line[2],
            "location" => $line[3],
        )
    }
    fclose($handle);
}
?>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement