Page 1 of 1

loop though text file

Posted: Sun Jul 21, 2013 12:38 pm
by inosent1
hi


i have a text file with 100 lines of data

i have the code to grab the text i am looking for in each line.

how do i read the text file, grab the text on each line, [process text - i have this code], then go to the next line in the text file, and just go down line by line until i get to the last line?

TIA

Re: loop though text file

Posted: Sun Jul 21, 2013 3:17 pm
by Celauran
Use file() to read the file into an array, then loop through the array?

Re: loop though text file

Posted: Sun Jul 21, 2013 3:31 pm
by mecha_godzilla
Hi,

Here is an example similar to what Celauran has just suggested:

Code: Select all

$filename_contents = file_get_contents('my_text_file.txt');
$lines = explode("\n", $filename_contents);
$number_of_lines = count($lines);

for ($i = 0; $i < $number_of_lines; $i++) {
	
	$lines[$i] = chop($lines[$i]);
	echo $lines[$i] . '<br />';
	
}
Note that text files saved on either Windows or Un*x will work because the end of line (EOL) character will still be matched even though their EOL characters are different ("\n" for Un*x, "\r\n" for Windows) but this might not work with files saved on Mac. Technically, Mac OS X is Un*x now anyway but some applications use the older Mac EOL ("\r") character.

HTH,

Mecha Godzilla

Re: loop though text file

Posted: Sun Jul 21, 2013 3:46 pm
by inosent1
thanks. works perfectly

Re: loop though text file

Posted: Mon Jul 22, 2013 9:49 am
by AbraCadaver
I would use Celauran's suggestion as it is:

Code: Select all

$lines = file('file.txt', FILE_IGNORE_NEW_LINES);
foreach($lines as $line) {
    //do something with $line
}