CSV into array

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
PHP Gurus...

Can anyone give me a helping hand with this.

I'm more ASP, but trying to move to PHP and sturggling a bit.

I have a few products stored in a csv file created in Excel. Column 1
is the part #, column 2 is title, column 3 is color, column 4 is width
and 5 is price.

I need to read these into arrays, with a seperate array for each

Can anyone suggest anything?

If someone could point me in the right direction it would be much


Re: CSV into array

Tom wrote:

Quoted text here. Click to load it

Hi Tom,

Try something like this:
1) find out what the end-of-line is. Probably \n
2) read the csv into an array using file().
Now each arrayelement is a row from the csv.
check www.php.net for details.

3) Explode each line, using the seperator for columns. (can be tab \t or ,  
or whatever you decided.)

Good luck.

Erwin Moller

Re: CSV into array

Quoted text here. Click to load it


have a look at this function, and see if it helps you




Re: CSV into array

Tom wrote:

Quoted text here. Click to load it

Try something like:


$lines =file('whatever.csv');

foreach($lines as $line)
        list($partno[],$title[],$color[], ... )
                = explode(',',$line);

Keep in mind that all CSV files are not equal: some use other delimiter than
comma for separating fields, some encapsulate fields within double quotes,
etc. The above code is for a trivial CSV file.

Iván Sánchez Ortega -ivansanchez-arroba-escomposlinux-punto-org

TAG no encontrado... Insert disk #2

Re: CSV into array

Great, thanks for the tips. I've managed to overcome the hard bit now

I've encountered a small problem that I can't figure out though....

My 1st page is a table with each of the products listed, with a
quantity form field for each product. The name of this field is qty1,
qty2 etc depending on which product it is. With me so far I hope....

The next page calls up the CSV again and loops through each line. I now
want to request the quantity form field for each product.

So I'm trying this

function convertCSVtoAssocMArray($file, $delimiter)
   $result = Array();
   $size = filesize($file) +1;
   $file = fopen($file, 'r');
   $keys = fgetcsv($file, $size, $delimiter);
   while ($row = fgetcsv($file, $size, $delimiter))
       for($i = 0; $i < count($row); $i++)
           if(array_key_exists($i, $keys))
               $row[$keys[$i]] = $row[$i];
       $result[] = $row;
return $result;

$myarray = convertCSVtoAssocMArray("sscreen.csv", ",");

$numElements = count($myarray);

for($counter=0; $counter < $numElements; $counter++)
$unitprice = $qty * $myarray[$counter][4];
echo $qty[$counter];
echo $counter;

But nothing is outputting! Any ideas? I basically need to construct the
$qty1 variable by adding the record count onto the end.

Again, thanks for all your help!


Re: CSV into array

Quoted text here. Click to load it

Try adding this line after the one quoted above:

   print_r( $myarray );

and see if what you get in the array matches your expectations.


Re: CSV into array

On Wed, 12 Oct 2005 01:18:07 -0700, Tom wrote:

Quoted text here. Click to load it

example of how I woud do it: (WARNING: Untested code!)

$file = file("theFile.csv");
foreach ($file as $line){
    list($row[$r]['partno'], $row[$r]['title'], $row[$r]['color'],
         $row[$r]['width'], $row[$r]['price']) = split(",", $line);

That puts the whole file into a 2-dimensional arra ($row) that simulates
the layout of the Excel sheet. Do whatever you wnat with it after that.

    JDS | jeffrey@example.invalid
        | http://www.newtnotes.com
  DJMBS | http://newtnotes.com/doctor-jeff-master-brainsurgeon/

Re: CSV into array

Tom wrote:
Quoted text here. Click to load it

  $maxlinelength = 1000;
  $fh = fopen('inventory.csv', 'r');
  $firstline = fgetcsv($fh, $maxlinelength);
  $cols = count($firstline);

  $row = 0;
  $inventory = array();
  while ( ($nextline = fgetcsv($fh, $maxlinelength)) !== FALSE )
    for ( $i = 0; $i < $cols; ++$i )
      $inventory[$firstline[$i]][$row] = $nextline[$i];

That puts the data in the array $inventory where $inventory['partno'][10]
is the 11th item in the 'partno' column. Column headings from the csv file
are used as keys for the associative array $inventory. You may address the
columns as "separate arrays" like so: $inventory['partno'] which is in
itself a numerically indexed array with 0 <= index < $row.

E. Dronkert

Site Timeline