How to Parse a CSV File in PHP?

Comma-Separated Values (CSV) files are a common way to store and exchange tabular data.

In PHP, you can easily parse CSV files to work with their contents, whether you need to read data from a CSV file, process it, or import it into a database.

In this article, we'll explore how to parse a CSV file in PHP using different methods.

1. Using "fgetcsv" function

The fgetcsv function is a straightforward way to read and parse a CSV file line by line. Here's a simple example:

$file = fopen('example.csv', 'r'); // Open the CSV file for reading

if ($file !== false) {
    while (($row = fgetcsv($file)) !== false) {
        // $row is an array containing the CSV columns
        print_r($row);
    }

    fclose($file); // Close the CSV file
}

In this code:

  1. We use fopen to open the CSV file for reading, specifying the file's name and the read mode ('r').
  2. Inside the while loop, we use fgetcsv to read a line from the CSV file. It returns an array where each element corresponds to a column in the CSV.
  3. We can then process the data in the $row array as needed.
  4. Finally, we close the file using fclose.

2. Using "str_getcsv" with File Contents

If you have the entire CSV file contents as a string, you can use the str_getcsv function to parse it. Here's an example:

$csvData = file_get_contents('example.csv'); // Read the CSV file into a string
$rows = str_getcsv($csvData, "\n"); // Split the CSV into rows

foreach ($rows as $row) {
    $columns = str_getcsv($row); // Split the row into columns
    print_r($columns);
}

In this code:

  1. We use file_get_contents to read the CSV file and store its contents in the $csvData variable.
  2. We split the CSV into rows using str_getcsv by specifying "\n" (newline) as the delimiter. This gives us an array of rows.
  3. We then iterate through the rows and split each row into columns using str_getcsv without a delimiter. This allows it to automatically detect and split columns using commas.
  4. Finally, we can process the data in the $columns array.

3. Using fgetcsv with Stream Context

If you need to fetch a CSV file from a URL or other external source, you can use fgetcsv with a stream context to open and parse it. Here's an example:

$csvURL = 'https://example.com/data.csv'; // Replace with the CSV file's URL
$context = stream_context_create(['http' => ['header' => 'User-Agent: PHP']]);

$file = fopen($csvURL, 'r', false, $context);

if ($file !== false) {
    while (($row = fgetcsv($file)) !== false) {
        print_r($row);
    }

    fclose($file);
}

In this code:

  1. We specify the CSV file's URL in the $csvURL variable.
  2. We create a stream context using stream_context_create. In this example, we also set a User-Agent header to identify the request as coming from PHP.
  3. We use fopen with the stream context to open the remote CSV file for reading.
  4. The parsing and processing of the CSV data within the while loop are similar to the first method.

Conclusion

Parsing CSV files in PHP is a fundamental task when working with tabular data. Whether you have a local CSV file or need to fetch it from an external source, PHP provides several methods for reading and processing the CSV data.

The method you choose depends on your specific use case and the source of the CSV data. Understanding how to parse CSV files in PHP is essential for working with data efficiently and accurately.