Jump to content

Export array to csv

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
auroraswim

auroraswim

    Newbie

  • Members
  • PipPip
  • 12 posts
Hi

I have partially sorted a problem I have. I have created an
array ($arr[]=$row['TimeID'] =  array("time" => array( $row['HouseName'],$row['Day'],$row['StartTime'], $row['FinishTime'],$hours, $we, $dateSunday, $row['Type'] , $row['Name'], $row['PayrollID']))
;)

This works well. I now want to export this information to a csv.

I get a csv but all the information is in one column not in rows; this is the code I am using to create the rows in the csv - I am puzzled as to how I can get each row horizontally and then automatically go to the next row at the end of the line.

$fhandle = fopen($file, "w");
foreach ($arr as $k => $v)
  {
   foreach($v as $k1 =>$v1){
     foreach($v1 as $k2 =>$v2){     
      fputcsv($fhandle,split('"',$v2));
  }     
  }
}

Any ideas?

Thanks for your help.

Edited by Jaan, 02 April 2010 - 04:39 AM.
Please use code tags when you are posting your codes!


#2
auroraswim

auroraswim

    Newbie

  • Members
  • PipPip
  • 12 posts
sorry I must have accidentally clicked the wink???

#3
auroraswim

auroraswim

    Newbie

  • Members
  • PipPip
  • 12 posts
Hi I sorted the problem and this is the code that worked for me

$fp = fopen($file, "w");
ksort($arr);

$csv = "House,hours,Type,Name,PayrollID\r\n";
foreach($arr as $row){
    foreach($row as $value){
    $csv .= "{$value[0]},{$value[4]}, {$value[7]}, {$value[8]}, {$value[9]}\r\n";
}
}
fwrite ($fp, $csv);
fclose($fp);

Edited by Jaan, 02 April 2010 - 04:39 AM.
Please use code tags when you are posting your codes!


#4
SoN9ne

SoN9ne

    Programmer

  • Members
  • PipPipPipPip
  • 129 posts
This would also work.
$fp = fopen($file, "w");
ksort($arr);

$csv = "House,hours,Type,Name,PayrollID\r\n";
foreach($arr as $row){
     foreach($row as $value){
	     $csv .= implode( ',', $value ) . "\r\n";
     }
}
fwrite ($fp, $csv);
fclose($fp);

By using implode you won't need to edit the value area when adding new fields but you will still need to add header fields.