6.10 Displaying a Textfile to the User


6.10 Displaying a Textfile to the User

You want to print an entire textfile to the user, but do not want to have to loop through the file line-by-line .

Technique

If you want to work with part of a file and then pass through the rest of the file to the screen, use fpassthru() . The fpassthru() function takes a file pointer and " passes thru" the remaining contents of the file to standard output ( STDOUT ):

 <?php $fp = @fopen("some_file.txt", "r")   or die ("");     $twenty_bytes = fread($fp, 20);     fpassthru ($fp); // Print out the rest of the file @fclose ($fp); ?> 

If you just want to print the entire file, use the readfile() function:

 <?php     readfile ("http://www.perl.com/"); ?> 

You can also use a combination of file() and implode() to print a complete file:

 <?php     print implode ("\n", file ('http://www.webreference.com')); ?> 

Comments

The last solution is sort of a hack. What we do is fetch the specified file as an array of lines, and then implode (join) that array around the newline ( \n ) character. Unless you are fetching the entire file into a variable, it is much better to use the readfile() function for these cases. The readfile() function is basically like fpassthru() without the fat: It opens a file and prints it to the browser.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net