Character Separated Values(CSV) or Comma Separated Values is a file type containing plain text content with a comma or a character as separators. PHP provides built-in functionality to read CSV files.
Here, we will learn to use CSV data in our application using multiple methods.
- Read CSV File using PHP fgetcsv()
- PHP CSV String Data Read
The first method will read data from a file while we can use the second method to read data from any variable.
Read CSV File using PHP fgetcsv()
To read CSV files PHP provides the fgetcsv() function. This function will read files and check CSV fields.
The fgetcsv() function can require one parameter which is the file pointer. There are some other optional arguments that we can use as per our requirements like the length for setting the maximum length of loop, delimer or encloser. Let’s take an example for it:
<?php
$row = 1;
if (($handle = fopen("FILE_NAME.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($i=0; $i < $num; $i++) {
echo $data[$i] . "<br />\n";
}
}
fclose($handle);
}
?>
In the above example, we have an open file in reading mode just like a regular file. Then we will use the fgetcsv() function and here we have a defined limit of 1000 records and it will loop each record. Lastly, we just print data to a user.
Here, we also have displayed row numbers while looping every time.
PHP CSV String Data Read
The str_getcsv() function is used for reading CSV data from a string or variable. Below is a syntax for the function:
str_getcsv($csv_string,$separator,$enclosure,$escape_character)
It’s’ works the same as the fgetcsv() function where it takes a CSV string or variable as a required parameter and the same optional parameters as the previous function. Let’s take an example for the str_getcsv() function:
<?php
$colors = '"RED","#D62433"
"ORANDE","#FEB635"
"YELLOW","#FEE492"
"GREEN","#9BA207"
"BROWN","#922E2F"';
$data = str_getcsv($str_CSV, "\n");
$length = count($data);
for($i = 0; $i < $length; $i++) {
$data = str_getcsv($data[$i], ",");
print_r($data);
}
?>
Here, we have defined CSV data into colors variable and converted that string into an array using the str_getcsv() function. Then simply loop through that array and print its content.
Conclusion
In this article, we have read CSV data from files as well as from string variables using in-built PHP functions fgetcsv() and str_getcsv() functions. In practical use, we can use this functionality to import data to a database or store and display data from CSV files to the user.