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

Asked

Viewed 7,910 times

5

I’m not sure I can read a file .txt and store your data in different positions in one 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’d 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, he is storing it all within a single position! And in case I’d 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;
  • And what are the criteria? each file row in an array position?

  • The criteria would be: $arrM[0] = city=A(100,80); $arrM[1] = city=B(160,70); $arrM[2] = city=C(110,50);

2 answers

2

If the file is not too 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>';
}
  • in the case of file(), it is possible to use a delimiter to separate it according to my last edit of the question? @rray

  • @Luizfelipe You can’t just do echo $f[0];?

2


Follow below another way using the 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;
  • 2

    That’s just what I needed !! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.