Wednesday, October 14, 2009

Reading Lines of Text: fgets








Reading Lines of Text: fgets


You can use the fgets function to get a string of text from a file; here's how you use it in general:



fgets (resource handle [, int length])


You pass this function the file handle corresponding to an open file, and an optional length. The function returns a string of up to length - 1 bytes read from the file corresponding to the file handle. Reading ends when length - 1 bytes have been read, on a newline (which is included in the return value), or on encountering the end of file, whichever comes first. If no length is specified, the length default is 1024 bytes.


Let's see an example, phpreadfile.php. Say you have a file, file.txt, in the same directory as phpreadfile.php, and you want to read its contents:



Here
is
the
text.


After opening the file for reading, we'll read it line by line with fgets. To loop over all the lines in the file, you can use a while loop and the feof function, which returns TRUE when you've reached the end of the file:



<?php
$handle = fopen("file.txt", "r");
while (!feof($handle)){
.
.
.
}
?>


Now all we've got to do is to read text lines using fgets and echo the text:



<?php
$handle = fopen("file.txt", "r");
while (!feof($handle)){
$text = fgets($handle);
echo $text, "<BR>";
}
?>


When you're done with the file, you close the file handle with fclose:



<?php
$handle = fopen("file.txt", "r");
while (!feof($handle)){
$text = fgets($handle);
echo $text, "<BR>";
}
fclose($handle);
?>


You can see this all at work in phpreadfile.php, Example 7-6.


Example 7-6. Accessing base class methods, phpreadfile.php



<HTML>
<HEAD>
<TITLE>
Reading a file
</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1>
Reading a file
</H1>
<?php
$handle = fopen("file.txt", "r");
while (!feof($handle)){
$text = fgets($handle);
echo $text, "<BR>";
}
fclose($handle);
?>
</CENTER>
</BODY>
</HTML>



That's it; you can see the results in Figure 7-6.


Figure 7-6. Reading from a file.

[View full size image]









    No comments:

    Post a Comment