File Function (returning multiple lines from a file)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

File Function (returning multiple lines from a file)

Post by Templeton Peck »

How can I make the following code return more then one line from the file read in? right now it will only return the first line from the file and thats it


<?php
function getFile( $FN )
{
if(!file_exists($FN))
{
echo 'Bad file name';
return;
}

$fp = fopen ($FN, "r");

while($line = fgets($fp, 1024))
{
list($project_number,$workpackage_number,$employee_number,$date,$number_of_hours)= explode(",",$line);

$oneline = array($project_number,$workpackage_number,$employee_number,$date,$number_of_hours);

return $oneline;

}

fclose($fp);
}

$man = array();
$man = getFile("timerecords.txt");

for($i = 0; $i < count($man); $i++)
{
echo $man[$i];
}
?>
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

You could try this:

test.php:

Code: Select all

<?php
function getFile( $FN ) {
	if(!file_exists($FN)) {
		echo 'Bad file name';
		return;
	}
	$fp = fopen ($FN, "r");
	while($line = fgets($fp, 1024)) {
		list($project_number,$workpackage_number,$employee_number,$date,$number_of_hours)= explode(",",$line);
		$oneline[] = array($project_number,$workpackage_number,$employee_number,$date,$number_of_hours); //append to $oneline
	}
	fclose($fp);
	return $oneline;//return on function's end
}

$man = array();
$man = getFile("timerecords.txt");

for($i = 0; $i < count($man); $i++)
	print_r($man[$i]);
?>
timerecords.txt:

Code: Select all

a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
teste.php output:

Code: Select all

Array
(
    &#1111;0] =&gt; a1
    &#1111;1] =&gt; b1
    &#1111;2] =&gt; c1
    &#1111;3] =&gt; d1
    &#1111;4] =&gt; e1

)
Array
(
    &#1111;0] =&gt; a2
    &#1111;1] =&gt; b2
    &#1111;2] =&gt; c2
    &#1111;3] =&gt; d2
    &#1111;4] =&gt; e2

)
I hope it helps.

Cheers,
Scorphus.
User avatar
Templeton Peck
Forum Commoner
Posts: 45
Joined: Sun May 11, 2003 7:51 pm

Post by Templeton Peck »

thanks :)

everythings going smooth now
Post Reply