Parsing CSV Files with PHP

Home » Coding » Parsing CSV Files with PHP

Parsing CSV Files with PHP

Learn how to read and process CSV files in PHP using the fgetcsv() function, and convert CSV data into arrays for easy manipulation.

Comma Separated Value (CSV) files are used extensively for exchanging data between different systems. CSV files are structured in a tabular form like an Excel Spreadsheet. Each row of the CSV file defines a record or entry, and each column represents the fields of that entry. A CSV file can be easily created or edited using most spreadsheet applications like LibreOffice or MS Excel.

PHP provides a simple built-in function fgetcsv() to read CSV files. This guide demonstrates how you can use fgetcsv() to read CSV data into an array to process the values programmatically.

Understanding fgetcsv()

fgetcsv() is a PHP function that reads lines from a CSV file and parses them into a numerically indexed array. The function accepts three parameters:

  • file handler: The first parameter is a file pointer, a reference to a CSV file that the function is to read.
  • length: The second parameter is an integer value determining the maximum length of a line to read.
  • delimiter: The third parameter is an optional character that specifies the CSV delimiter. The default delimiter in PHP is a comma character.

The fgetcsv() function returns an array containing the CSV fields on success and FALSE on failure (e.g. if the end of the file is reached).

Here's a simple snippet demonstrating how you can use fgetcsv() to print all rows and columns of a CSV file.

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p>Line $row contains $num fields:<br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

In this code snippet:

  • fopen() opens the CSV file called "test.csv" with mode "r" i.e., read-only. This function returns a reference to the file pointer stored in $handle.
  • fgetcsv() reads a line from the CSV file and parses its contents into an array $data.
  • The 1000 parameter in the fgetcsv function specifies the maximum length of a line to be read from the CSV file. A line in the CSV file will be truncated if it exceeds this length.
  • count() returns the number of elements in the $data array.
  • A loop then iterates through each element of the $data array, printing it to the screen.

Parsing CSV files into an Array

Let's now look at how you can take the data from a CSV file and convert it into an array, which is much more convenient for processing and manipulation.

Consider the following CSV file:

Name, Age, Country
Adam, 25, USA
Bob, 33, Canada
Charlie, 19, Australia

Here's how you can read this file and store its contents in an array:

<?php

$csv = array_map('str_getcsv', file('test.csv'));
$header = array_shift($csv);
$result = array();
foreach ($csv as $row) {
    $result[] = array_combine($header, $row);
}

In this code snippet:

  • file('test.csv') reads the entire CSV file into an array of strings, with each array element containing one line of the file.
  • array_map('str_getcsv', ...) maps each line to an array of string values, with each value containing one column of the CSV.
  • array_shift() retrieves and removes the first element of the $csv array, which contains the column headers (i.e., "Name", "Age", "Country").
  • $result is then constructed by iterating through each row of the $csv array and using the array_combine() function to create an associated array where each header value corresponds to that row's column value.

After running this code, $result should contain the following values:

<?php

$result = array(
    array("Name" => "Adam", "Age" => 25, "Country" => "USA"),
    array("Name" => "Bob", "Age" => 33, "Country" => "Canada"),
    array("Name" => "Charlie", "Age" => 19, "Country" => "Australia")
);

Conclusion

CSV files are a flexible and convenient way to transfer data in a structured manner, and PHP provides an easy way to read and process them. The fgetcsv() function makes it simple to read CSV data line-by-line, while the array_map() and array_combine() functions can be used to convert CSV data into arrays for further processing.

With this guide, you should now have the knowledge you need to work with CSV data in your PHP applications.


Details

  • Title: Tutorial: How to Parse CSV using PHP
  • Published:
  • Author:
  • Categories: PHP
Top Hosting Providers
Price

Want help?

Sometimes it can be hard to make a choice. Have you still not foun the information you're looking for, or are you wondering about something specific? Get in touch and we'll help you out.

Get in touch