Home > Article > Backend Development > Summary of PHP file reading and writing skills
Summary of PHP file reading and writing skills
Introduction:
PHP is a widely used scripting language that is used for Web development. Reading and writing files is a common operation during web development. This article will summarize some common PHP file reading and writing techniques and provide corresponding sample code.
1. File reading skills
Use the file_get_contents() function to read the entire file content:
Code example:
$file_content = file_get_contents('example.txt'); echo $file_content;
Use the fgets() function to read the file content line by line:
Code example:
$file = fopen('example.txt', 'r'); while (($line = fgets($file)) !== false) { echo $line; } fclose($file);
Use the fread() function to read the file content by the specified number of bytes:
Code sample:
$file = fopen('example.txt', 'r'); $file_content = fread($file, 1024); echo $file_content; fclose($file);
Use the file() function to read the file contents into an array:
Code sample:
$file_lines = file('example.txt'); foreach ($file_lines as $line) { echo $line; }
2. File writing skills
Use the file_put_contents() function to write file contents:
Code example:
$data = "Hello, World!"; file_put_contents('example.txt', $data);
Use The fputs() function writes the file content:
Code example:
$file = fopen('example.txt', 'w'); $data = "Hello, World!"; fputs($file, $data); fclose($file);
Use the fwrite() function to write the file content:
Code example:
$file = fopen('example.txt', 'w'); $data = "Hello, World!"; fwrite($file, $data); fclose($file);
Use append mode ('a') to open the file and write the content:
Code example:
$file = fopen('example.txt', 'a'); $data = "Hello, World!"; fwrite($file, $data); fclose($file);
3. Case - Statistics of file lines
The following is a case of using file reading techniques to count the number of lines in a given file:
Code example:
$file = fopen('example.txt', 'r'); $line_count = 0; while (($line = fgets($file)) !== false) { $line_count++; } fclose($file); echo "总行数:" . $line_count;
Summary:
This article introduces some common PHP file reading and Writing techniques are explained with corresponding code examples. File reading operations can use the file_get_contents()
, fgets()
, fread()
and file()
functions; file writing Operations can use the file_put_contents()
, fputs()
and fwrite()
functions. Using these techniques, you can easily perform file reading and writing operations and improve development efficiency.
The above is the detailed content of Summary of PHP file reading and writing skills. For more information, please follow other related articles on the PHP Chinese website!