How to create an array from a CSV file using PHP and the fgetcsv function

Can someone kindly provide code to create an array from a CSV file using fgetcsv?

I used the following code to create an array from a simple CSV file, but it does not work correctly if one of my fields has multiple commas - for example, addresses.

$lines =file('CSV Address.csv'); foreach($lines as $data) { list($name[],$address[],$status[]) = explode(',',$data); } 

* In addition, the str_getcsv function is not supported by my hosting service.

The above code does not work with the following example CSV file. The first column is the name, the second column is the address, the third is family.

 Scott L. Aranda,"123 Main Street, Bethesda, Maryland 20816",Single Todd D. Smith,"987 Elm Street, Alexandria, Virginia 22301",Single Edward M. Grass,"123 Main Street, Bethesda, Maryland 20816",Married Aaron G. Frantz,"987 Elm Street, Alexandria, Virginia 22301",Married Ryan V. Turner,"123 Main Street, Bethesda, Maryland 20816",Single 
+67
arrays php csv
Aug 13 '09 at 1:18
source share
11 answers

As you said in your title, fgetcsv is the way to go. It is pretty easy to use.

 $file = fopen('myCSVFile.csv', 'r'); while (($line = fgetcsv($file)) !== FALSE) { //$line is an array of the csv elements print_r($line); } fclose($file); 

You will want to put additional error checking there if fopen() fails, but this works to read the CSV file line by line and parse the line in the array.

+124
Aug 13 '09 at 1:41
source share

I think the str_getcsv () syntax is much cleaner, it also does not require CSV to be saved in the file system.

 $csv = str_getcsv(file_get_contents('myCSVFile.csv')); echo '<pre>'; print_r($csv); echo '</pre>'; 

Or for a linear solution:

 $csv = array(); $lines = file('myCSVFile.csv', FILE_IGNORE_NEW_LINES); foreach ($lines as $key => $value) { $csv[$key] = str_getcsv($value); } echo '<pre>'; print_r($csv); echo '</pre>'; 

Or for a linear solution without str_getcsv ():

 $csv = array(); $file = fopen('myCSVFile.csv', 'r'); while (($result = fgetcsv($file)) !== false) { $csv[] = $result; } fclose($file); echo '<pre>'; print_r($csv); echo '</pre>'; 
+39
Aug 13 '09 at 2:20
source share

I created a function that converts a csv string to an array. The function knows how to escape from special characters, and works with or without body characters.

I tried this with your csv sample and it works as expected!

 function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") { // @author: Klemen Nagode $array = array(); $size = strlen($string); $columnIndex = 0; $rowIndex = 0; $fieldValue=""; $isEnclosured = false; for($i=0; $i<$size;$i++) { $char = $string{$i}; $addChar = ""; if($isEnclosured) { if($char==$enclosureChar) { if($i+1<$size && $string{$i+1}==$enclosureChar){ // escaped char $addChar=$char; $i++; // dont check next char }else{ $isEnclosured = false; } }else { $addChar=$char; } }else { if($char==$enclosureChar) { $isEnclosured = true; }else { if($char==$separatorChar) { $array[$rowIndex][$columnIndex] = $fieldValue; $fieldValue=""; $columnIndex++; }elseif($char==$newlineChar) { echo $char; $array[$rowIndex][$columnIndex] = $fieldValue; $fieldValue=""; $columnIndex=0; $rowIndex++; }else { $addChar=$char; } } } if($addChar!=""){ $fieldValue.=$addChar; } } if($fieldValue) { // save last field $array[$rowIndex][$columnIndex] = $fieldValue; } return $array; } 
+14
Feb 12 2018-11-11T00:
source share

An old question, but still relevant for PHP 5.2 users. str_getcsv is available from PHP 5.3. I wrote a small function that works with fgetcsv itself.

Below is my function from https://gist.github.com/4152628 :

 function parse_csv_file($csvfile) { $csv = Array(); $rowcount = 0; if (($handle = fopen($csvfile, "r")) !== FALSE) { $max_line_length = defined('MAX_LINE_LENGTH') ? MAX_LINE_LENGTH : 10000; $header = fgetcsv($handle, $max_line_length); $header_colcount = count($header); while (($row = fgetcsv($handle, $max_line_length)) !== FALSE) { $row_colcount = count($row); if ($row_colcount == $header_colcount) { $entry = array_combine($header, $row); $csv[] = $entry; } else { error_log("csvreader: Invalid number of columns at line " . ($rowcount + 2) . " (row " . ($rowcount + 1) . "). Expected=$header_colcount Got=$row_colcount"); return null; } $rowcount++; } //echo "Totally $rowcount rows found\n"; fclose($handle); } else { error_log("csvreader: Could not read CSV \"$csvfile\""); return null; } return $csv; } 

Returns

Start reading CSV

 Array ( [0] => Array ( [vid] => [agency] => [division] => Division [country] => [station] => Duty Station [unit] => Unit / Department [grade] => [funding] => Fund Code [number] => Country Office Position Number [wnumber] => Wings Position Number [title] => Position Title [tor] => Tor Text [tor_file] => [status] => [datetime] => Entry on Wings [laction] => [supervisor] => Supervisor Index Number [asupervisor] => Alternative Supervisor Index [author] => [category] => [parent] => Reporting to Which Position Number [vacant] => Status (Vacant / Filled) [index] => Index Number ) [1] => Array ( [vid] => [agency] => WFP [division] => KEN Kenya, The Republic Of [country] => [station] => Nairobi [unit] => Human Resources Officer P4 [grade] => P-4 [funding] => 5000001 [number] => 22018154 [wnumber] => [title] => Human Resources Officer P4 [tor] => [tor_file] => [status] => [datetime] => [laction] => [supervisor] => [asupervisor] => [author] => [category] => Professional [parent] => [vacant] => [index] => xxxxx ) ) 
+10
Nov 27 '12 at 6:37
source share
 $arrayFromCSV = array_map('str_getcsv', file('/path/to/file.csv')); 
+6
Oct 07 '14 at 21:40
source share

Try it.

 function getdata($csvFile){ $file_handle = fopen($csvFile, 'r'); while (!feof($file_handle) ) { $line_of_text[] = fgetcsv($file_handle, 1024); } fclose($file_handle); return $line_of_text; } // Set path to CSV file $csvFile = 'test.csv'; $csv = getdata($csvFile); echo '<pre>'; print_r($csv); echo '</pre>'; Array ( [0] => Array ( [0] => Project [1] => Date [2] => User [3] => Activity [4] => Issue [5] => Comment [6] => Hours ) [1] => Array ( [0] => test [1] => 04/30/2015 [2] => test [3] => test [4] => test [5] => [6] => 6.00 )); 
+4
Jul 04 '15 at 11:28
source share

Try this code:

 function readCsv($file) { if (($handle = fopen($file, 'r')) !== FALSE) { while (($lineArray = fgetcsv($handle, 4000)) !== FALSE) { print_r(lineArray); } fclose($handle); } } 
+1
Jul 25 '14 at 7:25
source share

This function will return an array with header values ​​as array keys.

 function csv_to_array($file_name) { $data = $header = array(); $i = 0; $file = fopen($file_name, 'r'); while (($line = fgetcsv($file)) !== FALSE) { if( $i==0 ) { $header = $line; } else { $data[] = $line; } $i++; } fclose($file); foreach ($data as $key => $_value) { $new_item = array(); foreach ($_value as $key => $value) { $new_item[ $header[$key] ] =$value; } $_data[] = $new_item; } return $_data; } 
+1
Feb 14 '15 at 11:32
source share

Please omit the links to the function from @knagode below, enhanced by the skip rows parameter. https://gist.github.com/gabrieljenik/47fc38ae47d99868d5b3#file-csv_to_array

 <?php /** * Convert a CSV string into an array. * * @param $string * @param $separatorChar * @param $enclosureChar * @param $newlineChar * @param $skip_rows * @return array */ public static function csvstring_to_array($string, $skip_rows = 0, $separatorChar = ';', $enclosureChar = '"', $newlineChar = "\n") { // @author: Klemen Nagode // @source: http://stackoverflow.com/questions/1269562/how-to-create-an-array-from-a-csv-file-using-php-and-the-fgetcsv-function $array = array(); $size = strlen($string); $columnIndex = 0; $rowIndex = 0; $fieldValue=""; $isEnclosured = false; for($i=0; $i<$size;$i++) { $char = $string{$i}; $addChar = ""; if($isEnclosured) { if($char==$enclosureChar) { if($i+1<$size && $string{$i+1}==$enclosureChar){ // escaped char $addChar=$char; $i++; // dont check next char }else{ $isEnclosured = false; } }else { $addChar=$char; } }else { if($char==$enclosureChar) { $isEnclosured = true; }else { if($char==$separatorChar) { $array[$rowIndex][$columnIndex] = $fieldValue; $fieldValue=""; $columnIndex++; }elseif($char==$newlineChar) { echo $char; $array[$rowIndex][$columnIndex] = $fieldValue; $fieldValue=""; $columnIndex=0; $rowIndex++; }else { $addChar=$char; } } } if($addChar!=""){ $fieldValue.=$addChar; } } if($fieldValue) { // save last field $array[$rowIndex][$columnIndex] = $fieldValue; } /** * Skip rows. * Returning empty array if being told to skip all rows in the array. */ if ($skip_rows > 0) { if (count($array) == $skip_rows) $array = array(); elseif (count($array) > $skip_rows) $array = array_slice($array, $skip_rows); } return $array; } 
0
Jan 09 '15 at 11:51 on
source share

To get an array with the correct keys, you can try the following:

 // Open file $file = fopen($file_path, 'r'); // Headers $headers = fgetcsv($file); // Rows $data = []; while (($row = fgetcsv($file)) !== false) { $item = []; foreach ($row as $key => $value) $item[$headers[$key]] = $value ?: null; $data[] = $item; } // Close file fclose($file); 
0
Aug 14 '17 at 14:02
source share

I came up with this pretty simple code. I think this can be useful for everyone.

 $link = "link to the CSV here" $fp = fopen($link, 'r'); while(($line = fgetcsv($fp)) !== FALSE) { foreach($line as $key => $value) { echo $key . " - " . $value . "<br>"; } } fclose($fp); 
0
Aug 25 '17 at 19:37
source share



All Articles