note 66674 deleted from function.fgetcsv by cmb
| From: | cmb@php.net | Date: | Tue, 09 Oct 2018 12:19:04 +0000 |
| Subject: | note 66674 deleted from function.fgetcsv by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-209406@lists.php.net to get a copy of this message | ||
Note Submitter: jon at jonhassall dot com
----
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