In PHP development, it is common to read data from external files for import or parsing. This article will introduce several common file reading methods, along with practical examples to help you efficiently import and parse data in PHP.
PHP offers several functions for reading files, including file_get_contents(), fread(), and fgets(), each suited to different use cases.
The file_get_contents() function reads the entire file content into memory as a string, which is ideal for small file reads.
$file = 'example.txt';
$data = file_get_contents($file);
echo $data;
The above code will read the content of example.txt and output it.
The fread() function reads a specified length of data from the file. It is suitable for reading larger files.
$file = 'example.txt';
$handle = fopen($file, 'r');
$data = fread($handle, filesize($file));
echo $data;
fclose($handle);
This code uses the fread() function to read the content of example.txt and then closes the file handle after reading.
The fgets() function reads file data line by line, making it suitable for handling large files.
$file = 'example.txt';
$handle = fopen($file, 'r');
while (!feof($handle)) {
$line = fgets($handle);
echo $line;
}
fclose($handle);
This code reads the content of example.txt line by line and prints each line.
In many applications, we need to import data from files into a database. Below is an example of importing data from a CSV file into a database.
$file = 'example.csv';
$handle = fopen($file, 'r');
$headers = fgetcsv($handle); // Read the CSV file header
while (($data = fgetcsv($handle)) !== false) {
// Add database insert logic here
}
fclose($handle);
This code uses fgetcsv() to read each row of the CSV file and then imports the data into the database. Developers can add the database insert logic inside the while loop as needed.
Sometimes, data in files is not stored in a fixed format and needs to be parsed before use. Below is an example of parsing JSON file data.
$file = 'example.json';
$data = file_get_contents($file);
$decoded_data = json_decode($data, true);
if ($decoded_data !== null) {
// Handle successful parsing
} else {
// Handle parsing failure
}
This code reads the content of the JSON file using file_get_contents() and parses it using json_decode(). If parsing is successful, the parsed data can be processed further; if parsing fails, appropriate error handling can be applied.
This article introduced how to read files in PHP and implement data import and parsing. Code examples were provided to help developers efficiently handle file data and improve project development efficiency.