How to read and write CSV data

Functions that read and write CSV files

Function Description
fgetcsv($file) Reads in a line of comma-separated values and returns them in an array.
fputcsv($file, $array) Writes the specified array to the specified file as a line of comma-separated values.

A simple CSV file

MMS-1234,Trumpet,199.95 
       MMS-8521,Flute,149.95      

Read tabular data from a CSV file

      $file = fopen('products.csv', 'rb');
      $products = array(); 
      while (!feof($file)) {
        $product = fgetcsv($file); 
        if ($product === false) {
          continue; 
        }
        $products[] = $product; 
        echo("<div>$product[0] | $product[1] | $product[2]<./div>");
      }

Write tabular data to a CSV file

       $products = array(array('MMS-1234', 'Trumpet', 199.95), array('MMS-8521', 'Flute', 149.95)); $file = fopen('products.csv', 'wb'); 
       foreach ($products as $product) {
         fputcsv($file, $product);
       } 
       fclose($file);

Description

Back