Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.