Charles Marsh
Charles Marsh

Reputation: 465

PHP output to CSV

I have the following PHP script which reads from two CSV files, At the moment I am putting the data into a table however I need it to output to a CSV file...

<?php

$products_file = fopen('Products.csv', 'r');
$manufacturers_file = fopen('Manufacturers.csv', 'r');

$manufacturers = array();

while (($manufacturers_line = fgetcsv($manufacturers_file)) !== FALSE) {

     $manufacturers[$manufacturers_line[0]] = $manufacturers_line [1];

    }

echo '<table><tr><th>SKU</th><th>Make and Model</th><th>Make and Model</th></tr>';

while (($products_line = fgetcsv($products_file)) !== FALSE ) {

  echo '<tr><td>'.$products_line[3].'</td><td>';

  echo $manufacturers[$products_line[5]];

  echo '</td><td>'.$products_line[4].'</td></tr>';
}

echo '</table>';

fclose($products_file);
fclose($manufacturers_file);

?>

How can I do this using fputcsv ?

Upvotes: 1

Views: 1699

Answers (3)

Martin
Martin

Reputation: 10563

You could also do it this way:

Declare $csv outside your while loop:

$csv = '';

Then in your while loop populate the variable:

$csv .= $products_line[3].','.$manufacturers[$products_line[5]].','.$products_line[4]."\n";

Then once outside your loop you can write $csv to a file:

$myFile = 'testFile.csv';
$fh = fopen($myFile, 'w') or die('cannot open file');
fwrite($fh, $csv);
fclose($fh);

Done!

Note the double quote around the \n. If you use single quotes the \n character will not have the expected result.

Upvotes: 3

Richard Adnams
Richard Adnams

Reputation: 3128

Looks like you just need to change where it renders the html table to write it to a csv file like this as from the PHP documentation:-

$fp = fopen('newfile.csv', 'w');

while (($products_line = fgetcsv($products_file)) !== FALSE )
{
  fputcsv($fp, $products_line);
}

fclose($fp);

Hope that helps.

Rick.

Upvotes: 3

Martin Hennings
Martin Hennings

Reputation: 16846

I'd suggest this:

$outfile = fopen('output.csv', 'w');

while (($products_line = fgetcsv($products_file)) !== FALSE 
      && fputcsv(
        array($products_line[3], $manufacturers[$products_line[5]], $products_line[4]
      ) !== FALSE) {
  echo '<tr><td>'.$products_line[3].'</td><td>';
  echo $manufacturers[$products_line[5]];
  echo '</td><td>'.$products_line[4].'</td></tr>';
}

First, a new array is being created with
array($products_line[3], $manufacturers[$products_line[5]], $products_line[4].
Then this array is being fed to fputcsv().

The above code outputs both csv and html. Remove the echo if you don't want html output.

Upvotes: 2

Related Questions