Last active
April 6, 2024 17:07
-
-
Save marcanuy/ae7a2d0ab167e8e616f3 to your computer and use it in GitHub Desktop.
Iterate through lines in an external file with PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$file = new SplFileObject("animals.csv"); | |
$file->setFlags(SplFileObject::READ_CSV); | |
foreach ($file as $row) { | |
list($animal, $class, $legs) = $row; | |
printf("A %s is a %s with %d legs\n", $animal, $class, $legs); | |
} | |
?> | |
#Contents of animals.csv | |
crocodile,reptile,4 | |
dolphin,mammal,0 | |
duck,bird,2 | |
koala,mammal,4 | |
salmon,fish,0 | |
#The above example will output something similar to: | |
A crocodile is a reptile with 4 legs | |
A dolphin is a mammal with 0 legs | |
A duck is a bird with 2 legs | |
A koala is a mammal with 4 legs | |
A salmon is a fish with 0 legs | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$filename = 'myfile.csv'; | |
$file = new SplFileObject($filename); | |
while (!$file->eof()){ | |
$line = $file->current(); | |
$file->next(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
while (!$file->eof()) repeats the last line because you don't see the eof until the read.
while($line = $file->current()) works better. It combines the read and the test.