Read text file and play content in positions in an array!

5

I am in doubt that I can read a .txt file and store its data in different positions in a array .

The file is saved as follows:

city=A(100,80);
city=B(160,70);
city=C(110,50);
city=D(140,120);
city=F(155,40);
city=G(210,60);
city=H(190,10);
city=I(170,110);
route=A-C;140;
route=A-D;155;
route=C-F;125;
route=D-B;115;
route=D-I;152;
route=B-F;119;
route=B-G;136;
route=G-F;133;
route=F-H;163;
route=I-H;197;

And I would like to read it and store it separately in the positions of a array .

<?php

$f = fopen("mapa.txt", "r");

while (!feof($f)) { 
     $arrM = explode(";",fgets($f)); 
}

fclose($f);

?>

In this example, it is storing it all within a single position! And in case I would like it to be stored like this:

$arrM[0] = city=A(100,80);
$arrM[1] = city=B(160,70);
$arrM[2] = city=C(110,50);
//.....

$arrM[] = route=A-C;140;
    
asked by anonymous 24.08.2016 / 01:17

2 answers

2

Here's another way using explode and file_get_contents :

$linhas = explode("\n", file_get_contents('mapa.txt'));

echo $linhas[0] . "\n"; // city=A(100,80);
echo $linhas[1] . "\n"; // city=B(160,70);
echo $linhas[2] . "\n"; // city=C(110,50);
echo $linhas[9] . "\n"; // route=A-D;155;
    
24.08.2016 / 01:54
2

If the file is not very large, you can use the function file() it will convert your file into an array.

$f = file("mapa.txt");
foreach($f as $item){
   echo $item .'<br>';
}
    
24.08.2016 / 01:21