PHP Variables from File
Today we will learn about fopen() function in php. fopen() function is used to open the file directly from the C directory or URL. It makes this function versatile. Fopen() has two main parameters: $filename, used for open a particular file and the mode of opening the file. For example :
Here, r is the mode that denotes the file is open for reading only.
The mode enables the user how to handle the file. fopen() is a complex function but still popular among the programmer.
Syntax for PHP Variables from Files:
For example :
$file = fopen("textfile.txt","r");
$text = fgets($file);
The output of the example is : Only fools leave away messages!
Let's understand the above code one by one :
The first line $file = fopen("textfile.txt","r");
This line asking PHP to open the file and also remembered the location by mentioning the file name within the parenthesis and r is the mode which suggested the function that it is only used to read. We are assigning this function into a variable called $file.
The second line is while ($file)
A while loop moved round and round until you tell it to stop. It goes round and round till the condition is true. The condition between the round brackets was $file.
Inside the while loop the first line is $text = fgets($file);
Here, we use the fgets() function to bring the line of text from our file and within the parenthesis we used $file variable. So, we gets the line and put that line into a variable called $text.
And, the next line is print $text."<br/>";
It is used to print the file and display on the browser.
The last line of the code is fclose($file);
This fclose() is used the tell the php that closed the file here.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.