Writing to a File
- Use
fopen()
with mode'w'
or'a'
to open a file pointer for writing. - Use
fwrite()
to write data to the file. - Close the file pointer using
fclose()
when done.
Example (Reading from a File):
// Open a file for reading
$handle = fopen("file.txt", "r");
// Read data from the file
while (($line = fgets($handle)) !== false) {
echo $line;
}
// Close the file handle
fclose($handle);
Example (Writing to a File):
// Open a file for writing (create if not exists, truncate if exists)
$handle = fopen("file.txt", "w");
// Write data to the file
fwrite($handle, "Hello, World!\n");
// Close the file handle
fclose($handle);
How to Read and Write from Files in PHP ?
In PHP, reading from and writing to files is a common task in web development, especially for tasks such as reading configuration files, processing data files, or logging information. PHP provides built-in functions for handling file operations, making it straightforward to perform file read and write operations.