note 104558 modified in function.str-getcsv by danbrown

From: Date: Thu, 23 Jun 2011 14:33:03 +0000
Subject: note 104558 modified in function.str-getcsv by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-180881@lists.php.net to get a copy of this message
Just another way to convert a csv file to an associative array. <?php // // Convert csv file to associative array: // function csv_to_array($input, $delimiter='|') { $header = null; $data = array(); $csvData = str_getcsv($input, "\n"); foreach($csvData as $csvLine){ if(is_null($header)) $header = explode($delimiter, $csvLine); else{ $items = explode($delimiter, $csvLine); for($n = 0, $m = count($header); $n < $m; $n++){ $prepareData[$header[$n]] = $items[$n]; } $data[] = $prepareData; } } return $data; } //----------------------------------- // //Usage: $csvArr = csv_to_array(file_get_contents('test.csv')); ?> --was-- Just another way to convert a csv file to an associative array. <? // // Convert csv file to associative array: // function csv_to_array($input, $delimiter='|') { $header = null; $data = array(); $csvData = str_getcsv($input, "\n"); foreach($csvData as $csvLine){ if(is_null($header)) $header = explode($delimiter, $csvLine); else{ $items = explode($delimiter, $csvLine); for($n = 0, $m = count($header); $n < $m; $n++){ $prepareData[$header[$n]] = $items[$n]; } $data[] = $prepareData; } } return $data; } //----------------------------------- // //Usage: $csvArr = csv_to_array(file_get_contents('test.csv')); ?> http://php.net/manual/en/function.str-getcsv.php

« previous php.notes (#180881) next »