PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

HOW TO READ FILES INTO AN ARRAY USING THE fgets() FUNCTION IN PHP

Sometimes it might be useful to read data from a file into an array. This can easily be achieved using the fgets() function of PHP as follows:

Example:

<?

$myFile="test.txt";
$fd=fopen($myFile, "r");
while(!feof($fh))
{
$lines[ ]=fgets($fd);
}
fclose($fd);

?>

In the above example, the fgets() function will read from the opened test.txt until it encounters an end of line or end of file, whichever comes first and stops. It then stores each line in array $lines where each line is an element of that array.

PHP also provides a shortcut way of doing the above as follows:

Example:

<?

$myFile="test.txt";
$lines=file($myFile);

?>

The file function file() opens the file and reads each line into array $lines where each line is an element of that array.



Home | Privacy Policy | Terms Of Use | Contact Us