Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to import csv file in PHP?
In PHP, you can import and read CSV files using the built-in fgetcsv() function. This function reads a line from a file pointer and parses it for CSV fields, making it easy to process CSV data row by row.
Syntax
The fgetcsv() function has the following syntax −
fgetcsv($handle, $length, $delimiter, $enclosure, $escape)
Parameters
- $handle − File pointer resource
- $length − Maximum line length to read
- $delimiter − Field delimiter (default: comma)
- $enclosure − Field enclosure character (default: double quote)
- $escape − Escape character (default: backslash)
Example
The following code demonstrates how to import and display CSV file contents −
<?php
$row = 1;
if (($handle = fopen("data.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p><br>";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br /><br>";
}
}
fclose($handle);
}
?>
How It Works
The code opens the CSV file in read mode using fopen(). Starting from row 1, it reads each line using fgetcsv() with a maximum length of 1000 characters. For each row, it counts the number of fields and displays both the field count and individual field contents. Finally, it closes the file handle with fclose().
Alternative Approach Using array_map()
For smaller CSV files, you can read all data at once −
<?php
$csvData = array_map('str_getcsv', file('data.csv'));
foreach($csvData as $row => $data) {
echo "Row " . ($row + 1) . ": " . implode(', ', $data) . "<br>";
}
?>
Conclusion
Use fgetcsv() for memory-efficient reading of large CSV files line by line, or array_map() with str_getcsv() for smaller files that can be loaded entirely into memory.
