PHP is a widely-used scripting language, commonly used for web development. Reading and writing files are common tasks in web development. This article summarizes some of the most commonly used PHP file reading and writing techniques, and provides corresponding example codes to help developers improve efficiency.
$file_content = file_get_contents('example.txt'); echo $file_content;
$file = fopen('example.txt', 'r'); while (($line = fgets($file)) !== false) { echo $line; } fclose($file);
$file = fopen('example.txt', 'r'); $file_content = fread($file, 1024); echo $file_content; fclose($file);
$file_lines = file('example.txt'); foreach ($file_lines as $line) { echo $line; }
$data = "Hello, World!"; file_put_contents('example.txt', $data);
$file = fopen('example.txt', 'w'); $data = "Hello, World!"; fputs($file, $data); fclose($file);
$file = fopen('example.txt', 'w'); $data = "Hello, World!"; fwrite($file, $data); fclose($file);
$file = fopen('example.txt', 'a'); $data = "Hello, World!"; fwrite($file, $data); fclose($file);
Below is an example using file reading techniques to count the number of lines in a given file:
Example code:$file = fopen('example.txt', 'r'); $line_count = 0; while (($line = fgets($file)) !== false) { $line_count++; } fclose($file); echo "Total number of lines: " . $line_count;
This article introduces several commonly used PHP file reading and writing techniques with code examples. Developers can use functions like `file_get_contents()`, `fgets()`, `fread()`, and `file()` for reading files, and functions like `file_put_contents()`, `fputs()`, and `fwrite()` for writing to files. Mastering these techniques will help improve development efficiency and simplify file operations.