How to read a CSV file in PHP

| | 1 min read

CSV (Comma Seperated Value) a type of file format generally used in some popular websites like google to save the contacts in a comma seperated values. CSV is also called as a character seperated values. Its a normal file type as like doc, pdf etc. In this file format the values are stored by seperating every sentences with some characters. The most used character to seperate the values is comma so it is used to called as comma seperated values rather than the character seperated values. So lets have a quick look on how to read the csv format files.

  
  function open_addressbook() {
    global $config;
    global $addressbook;
    if(isset($addressbook)) {
      return $addressbook;
    }
    $output = array();
    $filename = $config['file_name'];
    if(file_exists($filename)) {
      $file = fopen($filename,'r');
      if ($file !== FALSE) {
        while ($data = fgetcsv($file)) {
          $output[] = array (
                      'email' => $data[0],
                      'name' => $data[1],
                      'mobile' => $data[2],
                      'dob' => $data[3] 
                      );
        }
        fclose($file);
      }
    }
    $addressbook = $output;
    return $output;
 }
  

First store the filename in an variable. Then check whether that file exists or not, if exists then open the file in read mode. For reading the contents in comma separated values format, add a while loop to parse the contents of the file in csv fields. Declare an array and retrieve the contents of the file. After reading the content, close the file and return the array of fields.