note 66674 modified in function.fgetcsv by danbrown

From: Date: Sun, 17 May 2009 18:14:24 +0000
Subject: note 66674 modified in function.fgetcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155084@lists.php.net to get a copy of this message
I modified the code for my own purposes, to return an array with named keys for each field. I tried various alternatives, and this seems to work well with exported Excel data. <?php //Move through a CSV file, and output an associative array for each line ini_set("auto_detect_line_endings", 1); $current_row = 1; $handle = fopen("testdatasource.csv", "r"); while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE ) { $number_of_fields = count($data); if ($current_row == 1) { //Header line for ($c=0; $c < $number_of_fields; $c++) { $header_array[$c] = $data[$c]; } } else { //Data line for ($c=0; $c < $number_of_fields; $c++) { $data_array[$header_array[$c]] = $data[$c]; } print_r($data_array); } $current_row++; } fclose($handle); ?> Jon Hassall --was-- I modified the code for my own purposes, to return an array with named keys for each field. I tried various alternatives, and this seems to work well with exported Excel data. <pre><?php //Move through a CSV file, and output an associative array for each line ini_set("auto_detect_line_endings", 1); $current_row = 1; $handle = fopen("testdatasource.csv", "r"); while ( ($data = fgetcsv($handle, 10000, ",") ) !== FALSE ) { $number_of_fields = count($data); if ($current_row == 1) { //Header line for ($c=0; $c < $number_of_fields; $c++) { $header_array[$c] = $data[$c]; } } else { //Data line for ($c=0; $c < $number_of_fields; $c++) { $data_array[$header_array[$c]] = $data[$c]; } print_r($data_array); } $current_row++; } fclose($handle); //Look at my photos www.jonhassall.com ! ?></pre> Jon Hassall http://php.net/manual/en/function.fgetcsv.php

« previous php.notes (#155084) next »