Jump to content

PHP CSV columns


luminous

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/199772-php-csv-columns/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.