luminous Posted April 26, 2010 Share Posted April 26, 2010 I'm using a script that exports database details into a CSV file. I want to he script to work so that the data and headings are in columns like so: heading1 heading 2 heading 3 Data1 Data2 Data3 However with my current script I'm getting: Heading 1 Heading2 Heading 3 Data1 Data2 Data3 The data is from two seperate arrays ($columns and $data) and the following code is executed: public function build($columns, $data) { $csv = ''; // initialise csv variable foreach($columns as $heading) // csv column headings { $csv .= $heading.','; // concat heading onto row } $csv .= "\n"; // all the headings have been added so move to new line for csv content foreach($data as $row) // csv table content { foreach($columns as $column => $t) { echo $row[$column]; if(strpos($row[$column],',')) // if cell content has a comma in it... { // ...double any existing quotes to escape them... $row[$column] = str_replace('"','""',$row[$column]); // ...and wrap the cell in quotes so the comma doesn't break everything. $row[$column] = '"'.$row[$column].'"'; $csv .= "\n"; } $csv .= $row[$column].","; // concat the value onto the row if($t==end($columns)) { // if we're at the end of a row move to a new line for next row $csv .= "\n"; } } } return $csv; } Please any help would be appreicated! Quote Link to comment https://forums.phpfreaks.com/topic/199772-php-csv-columns/ Share on other sites More sharing options...
salathe Posted April 26, 2010 Share Posted April 26, 2010 It might be useful to look into using fputcsv which writes CSV formatted values to a file; if you need a string with the CSV formatted values, rather than writing to a file, there are ways to do that as well. Quote Link to comment https://forums.phpfreaks.com/topic/199772-php-csv-columns/#findComment-1048544 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.