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

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

Like you said in your title, fgetcsv is the way to go. It's pretty darn 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'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

Thanks Dave but your example only provides an array with the following three positions: $line0, $line1, and $line2. That is fine for the first line, but I need to create separate positions for 2nd, 3rd, 4th, etc. Lines. That way I can manipulate the lines separately.

Hope that makes sense – Thomas Aug 13 '09 at 2:19 2 @Thomas If you need an array of names, addresses, and statuses, you can just do what you're doing above: list($names, $addresses, $statuses) = $line; – Dave DeLong Aug 13 '09 at 3:09 Thanks again Dave! That was tripping me up. – Thomas Aug 13 '09 at 17:28.

I think the str_getcsv() syntax is much cleaner, it also doesn't require the CSV to be stored in the file system. $csv = str_getcsv(file_get_contents('myCSVFile. Csv')); echo ''; print_r($csv); echo ''; Or for a line by line solution: $csv = array(); $lines = file('myCSVFile.

Csv', FILE_IGNORE_NEW_LINES); foreach ($lines as $key => $value) { $csv$key => str_getcsv($value); } echo ''; print_r($csv); echo ''; Or for a line by line solution with no str_getcsv(): $csv = array(); $file = fopen('myCSVFile. Csv', 'r'); while (($result = fgetcsv($file))! == false) { $csv = $result; } fclose($file); echo ''; print_r($csv); echo.

FYI: str_getcsv() is only available from PHP 5.3.0 on. The project I am working on missed it by 1 version DOH! (we are using 5.2.9 atm).

– Jim Ford Sep 16 '09 at 19:15.

I have created function which converts csv string to array. Function knows how to escape special chars, works with or without enclosure chars ... I tried it 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=""){ $fieldValue.

=$addChar; } } if($fieldValue) { // save last field $array$rowIndex$columnIndex = $fieldValue; } return $array; }.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions