Sooner or later in our development career we have come across important data stored in a CSV file. Many pieces of software use it because it’s a simple way to export data. But, when it comes to consuming that data with programming languages, it’s not always that simple as double clicking and opening the file! The following article shows the most efficient ways to consume and read a CSV file with PHP.
The CSV File
In this tutorial, we will work initially with a very basic comma separated values file, but also later in the article, we can start to swap the delimiter with other special characters like semi-colons etc.
This will show that the functions used have the strength to ready any type of CSV file with ease. The following is the content of the file that is going to be played with in this article –
This,is,a,csv,file
You can easily create one yourself in Microsoft Excel, or simply copy and paste the above into a text file and rename the extension to .CSV.
Pre-requisites
PHP is shipped out of the box with certain native functions that are capable of reading files. So the only requisite that is needed for this article is that you have PHP 5.6 => installed.
Reading And Printing
You’ll be quite surprised on how extremely simple it is to consume a file with PHP, especially these types. Some of the PHP built in functions make a developers life easier, and this is one of them.
Here is a quick break-down of what is actually happening in the following code example.
- The
fOpen
function is used to simply select/specify the file name. This will give you aboolean
return value depending on if the file was found/present. - The
fgetcsv
is used to physically read the specified file infOpen
, as you can see in the code above,fgetcsv
requires thefOpen
object as a parameter. Note: the third parameter offgetcsv
is the delimiter, this could be a semi-colon, a comma or any other separating special character within the CSV file itself.
Example
if (($handle = fopen('csvfiletutorial.csv', 'r')) !== FALSE) { // Check the resource is valid
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // Check opening the file is OK!
for ($i = 0; $i < count($data); $i++) { // Loop over the data using $i as index pointer
echo $data[$i] . "<br />\n";
}
}
fclose($handle);
}
Output
This
is
a
csv
file
It’s as simple as that, with only two native PHP functions needed to complete the functionality it’s super-speedy to develop and execute.
References
Parsing A CSV To An Array
In the above example, if you take away all of the fluff around echoing the data to page, we are left with pre-parsed array ready for disposal. It’s the $data
variable within the code.
Example
if (($handle = fopen('csvfiletutorial.csv', 'r')) !== FALSE) { // Check the resource is valid
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { // Check opening the file is OK!
print_r($data); // Array
}
fclose($handle);
}
Output
Array ( [0] => This [1] => is [2] => a [3] => csv [4] => file )
In addition to above, you’ll be glad to hear that there is another quick way to do this. Taking away the boolean
checks you can use a function called array_map
by using str_getcsv
as it’s callback function. Let’s see it in action –
Example
$csv = array_map('str_getcsv', file('csvfiletutorial.csv'));
print_r($csv);
Output
Array ( [0] => Array ( [0] => This [1] => is [2] => a [3] => csv [4] => file ) )
This way is obviously quicker, but you have less control of what is truly going on, so that risk is up to you to take.
References
Summary
Is this the only way to read CSV files? Certainly not. There are plenty of third-party plugins that are capable of doing this with even further advanced functionality. But for pure-speed, PHP has these native functions ready to use. They do the job swiftly without the need for bulking out a project.
What’s also worth noting here is that fgetcsv
is more than capable of reading big-data files, as I’ve put this to the test in various use cases. So, in future, if you’re reading some super-sized files, consider this function as an alternative.