Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read from a file??

Status
Not open for further replies.

martinb7

Programmer
Jan 5, 2003
235
GB
hi, how do you read from a file?

this is my code so far:

Code:
<?php
$TheFile = &quot;root.php&quot;;
$Open = fopen($Filename, &quot;r&quot;);
	if($Open){
		$Data = file($TheFile);
			for($n = 0; $n < count($Data); $n++){
				$GetLine = explode(&quot;\t&quot;, $Data[$n]);
					echo(&quot;$GetLine[0]&quot;);
			}

fclose($Open);
	}else{
		echo(&quot;File error&quot;);
	}
?>

is there a better way of doing it? if so please say

any tutorials??

thanx


Martin

Computing help and info:

 
<?PHP
$fd=fopen(&quot;/tmp/afile&quot;,&quot;r&quot;);
while ($line=fgets($fd,1000))
{
$alltext.=$line;
}
fclose ($fd);
?>

Hope this help!

Sincerely,

Dan Grant
Lead programmer
dan at abusinesshosting dot com
 
hi, it doesn't display any errors, but its not displaying any code?

can you only read from a .txt file not .php?

thanx

Martin

Computing help and info:

 
martinb7:
Actually, a simpler script with the same functionality of xhtml101's example is:

Code:
<?php
$an_array = file('/tmp/afile');
?>

But what this script does is read the file into an array. You can output that array line-by-line.

If you want to stream a file out to the browser, then a script like:

Code:
<?php
readfile ('/tmp/afile');
?>

is probably the easiest way.

PHP has a lot of special-purpose functions for file manipulation.


It looks like you're taking each line of the file, treating tab-characters as columns, and outputting the first column of each line.

I would not read the whole file into an array for that. I strongly recommend that you process as-you-go unless you specifically need to keep the entire file in memory.

Something like:
Code:
<?php
$TheFile = &quot;root.php&quot;;
$Open = fopen($Filename, &quot;r&quot;);
if($Open)
{
	while ($line = fgets($Open);
	{
		$line = rtrim($line);
		$linearray = explode(&quot;\t&quot;, $line);
		print $linearray[0];
	}
	fclose($Open);
}
else
{
	echo(&quot;File error&quot;);
}
?>

Want the best answers? Ask the best questions: TANSTAAFL!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top