Reading out a CSV file in PHP

How to create an array from a CSV file

This blog post will teach you how to read out a csv file in PHP. The heavy lifting will be done by the handy PHP function called str_getcsv.

In this example we use a CSV file that contains a header row describing the different fields.

When your CSV is delimited by the , sign you can use the following function to read out the CSV file.

 /**
   * Processes a CSV file.
   * @return array
   */
  public function processCSV($path = 'my-test.csv') {

    $processed_csv = rows = header = array();

    $rows = array_map('str_getcsv', file($path));
    $header = array_shift($rows);

    foreach ($rows as $i=>$row) {
      $processed_csv[$i] = array_combine($header, $row);
    }

    return $processed_csv;
  }

When your CSV is delimited by the ; sign slightly have to tweak this function:

 /**
   * Processes a CSV file.
   * @return array
   */
  public function processCSV($path = 'my-test.csv') {

    $processed_csv = rows = header = array();

    $rows = array_map(function($v){ return str_getcsv($v, ";");}, file($path));
    $header = array_shift($rows);

    foreach ($rows as $i=>$row) {
      $processed_csv[$i] = array_combine($header, $row);
    }

    return $processed_csv;
  }

Questions, remarks or improvements? Don't hesitate to contact me.

Development

Meer leesvoer

I have been working on a Drupal 8 multisite and at some point I had to set up a new site in the structure. The...
Drupal
In this blog post you will learn how to add a theme field preprocess function in your theme.
Theming
In this blog post I show you how to login and logout from a Drupal 8 Back-end from an Ionic app
Drupal
It's quite easy to create a node with REST in Drupal 8, in this blog post I'll show you how to do it.
Drupal