In this article Reading from a File in PHP we give the information about PHP has several simple methods for reading from and writing to a file. To read from a file in PHP, fopen(), fread(), and fclose() are used.
Reading from and writing to a file in PHP
PHP has several simple methods for reading from and writing to a file. We will discuss here different types of file operation processes like reading, writing, and modifying data.
-
Reading from a File
To read from a file in PHP, fopen(), fread(), and fclose() are used. Here is an example:
Reading from a File
<?php
// open and read the file
$file = fopen(“example.txt”, “r”);
if ($file) {
$content = fread($file, filename(“example.txt”));
fclose($file);
echo $content;
} else {
echo “There was an error reading file!”;
}
?>
fopen(“file.txt”, “r”) : To open the file.
fread($file, filesize(“file.txt”)) : To read the file.
fclose($file) :To close the file.
-
Writing to a File
To write to a file in PHP we use fopen() and fwrite(). Here is an example:
Writing to a File
<?php
// open the file and write to it
$file = fopen(“example.txt”, “w”);
if ($file) {
fwrite($file, “This is new content.”);
fclose($file);
echo “The content has been successfully added to the file.”;
} else {
echo “There was an error writing to the file!”;
}
?>
fopen(“file.txt”, “w”) : Open the file in ‘write’ mode.
fwrite($file, “data”) : Write data to the file.
fclose($file) : Close the file.
-
Appending to a File
If you want to add new content to a file, use an (append) mode.
Appending to a File
<?php
// open the file and add it
$file = fopen(“example.txt”, “a”);
if ($file) {
fwrite($file, “\nThis is a new line.”);
fclose($file);
echo “New line has been added to the file.”;
} else {
echo “There was an error adding file!”;
}
?>
fopen(“file.txt”, “a”) : Open the file in ‘append’ mode.
fwrite($file, “\ntext”) : Add a new line to the file.
-
Handling Errors
If there is a problem reading or writing to the file, you can use fopen() and other functions to handle the error.
Error Handling Example
<?php
$file = fopen(“nonexistent.txt”, “r”);
if (!$file) {
echo “There was an error opening the file!”;
} else {
$content = fread($file, filesize(“nonexistent.txt”));
fclose($file);
echo $content;
}
?>
Conclusion
- In PHP, different modes (r, w, a) are used to read from and write to the file.
- It is possible to open a file through fopen() and add or read data through fwrite()/fread().
- To handle errors, the result of fopen() must be checked.
Some More:
POP- Introduction to Programming Using ‘C’
OOP – Object Oriented Programming
DBMS – Database Management System
RDBMS – Relational Database Management System
Join Now: Data Warehousing and Data Mining