Home > Article > Backend Development > PHP file operation example: reading CSV file
PHP is a popular programming language widely used in web development. In web applications, file operations are a basic and common function. This article will explain how to use PHP to read a CSV file and display it in an HTML table.
CSV is a common file format used to import tabular data into spreadsheet software such as Excel. CSV files usually consist of many lines, each line consisting of comma separated values. The first line usually contains column headers, which describe the meaning of each column value.
Here we will use the PHP built-in function fgetcsv() to read the CSV file. The fgetcsv() function reads and parses a row of data from a CSV file and puts it into an array.
First, we need to prepare a CSV file, which should meet the following requirements:
· Contains comma-separated columns
· Contains column headers
· File encoding is utf-8
For demonstration purposes we will use the following CSV file (file.csv):
name,age,gender
John,25, Male
Jane,22,Female
Bob,30,Male
Now we need to write PHP code to read the CSV file. Note that this code assumes your CSV file is in the same directory as your PHP file.
2c001d3212cf02a171caed2e7cc2ece7";
// Output table column header
echo "868c3f8d39a371013a78a87c30e1b0d8";
foreach ($headers as $header) {
echo "b4d429308760b6c2d20d6300079ed38e$header01c3ce868d2b3d9bce8da5c1b7e41e5b";
}
echo "fd273fcf5bcad3dfdad3c41bd81ad3e5";
// Output table data
foreach ($data as $row) {
echo "a34de1251f0d9fe1e645927f19a896e8" ;
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "fd273fcf5bcad3dfdad3c41bd81ad3e5";
}
echo "f16b1740fad44fb09bfe928bcc527e08";
?>
Explain the above code. First, we open the CSV file and read the first row (column headers) using the fgetcsv() function. We store this in the $headers array.
Next, we use a loop to iterate through each line of data in the remainder of the file. Each row of data is parsed by the fgetcsv() function and stored in the $data array.
Then, we close the file and output the HTML table. We use the $headers array to output the column headers of the table, and the $data array to output the data of the table.
Now you can copy the above code into a PHP file and run it on your web server. You will see an HTML table containing CSV data that looks like this:
name age gender
John 25 Male
Jane 22 Female
Bob 30 Male
Summary
In the process of web development, file operation is a basic and common function. Using PHP, you can easily read and manipulate a variety of file types, including CSV, a widely used format for data import and export. Using the fgetcsv() function, you can read a CSV file into PHP and convert it into a data format suitable for display in a web application.
The above is the detailed content of PHP file operation example: reading CSV file. For more information, please follow other related articles on the PHP Chinese website!