Page 1 of 1
count entries and echo results
Posted: Mon Aug 23, 2004 4:13 am
by fresh
Hey,
I have a text file that holds a list of names like so:
john
josh
jason
susan
each on their own line.. and I would like to open this file and count each entry and store that value in a variable, so I could then echo that value to my web page.. thanks

Posted: Mon Aug 23, 2004 4:33 am
by JayBird
This is one way
Code: Select all
$server_path = $_SERVER['DOCUMENT_ROOT'];
// open the data file
($fp = fopen($server_path."/path/to/datafile/names.txt", 'r')) or die ("Couldn't open the data file");
$count = 0;
// Iterate through each line of the file
while ( ! feof($fp) ) {
$count++;
}
// output the result
echo $count;
Posted: Mon Aug 23, 2004 5:19 am
by fresh
hey it isn't working, it just keeps looping and I keep getting a fatal error, maxim time 30 seconds allowed..
I am using that exact code above.. any help? Thanks

Posted: Mon Aug 23, 2004 5:20 am
by JayBird
show me the code you have done.
Have you got the correct path tot he file.
Posted: Mon Aug 23, 2004 5:32 am
by redmonkey
An alternative....
Code: Select all
<?php
if (FALSE !== ($lines = @file('/path/to/file')))
{
$n_lines = count($lines);
// for large files unset lines array unless you plan
// to use it for something else.
unset($lines);
}
else
{
// failed to open file
$n_lines = 0;
}
echo $n_lines;
?>
Posted: Mon Aug 23, 2004 5:36 am
by fresh
alright.. that works great, thank you guys
