Jump to content

[SOLVED] writing CSV file


abdfahim

Recommended Posts

Use this.

 

<?php
//head information for a csv file
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
Header("content-type: text/html");
header("Content-Disposition: attachment; filename=\"website-data.csv\";");
header("Content-Transfer-Encoding: binary");

//echo the first line to be the titles of the columns (notice the return at the end of the line)
echo '"product ID","ref","title","description","price"
';

//query the db for the information
$result = mysql_query("SELECT * FROM products");

//echo each record (notice the return at the end of the line)
while ($row = mysql_fetch_array($result)){
echo '"'.$row[product_id].'","'.$row[ref].'","'.$row[title].'","'.$row[description].'","'.$row[price].'"
';
}
?>

Link to comment
Share on other sites

Why go through the effort of writing out headers, you can just as easily do something like this:

<?php
$fh = fopen('test.csv','w');
$flds = array("product ID","ref","title","description","price");
fputcsv($fh,$flds);
$q = "select product_id,ref,title,description from yourtable";
$rs = mysql_query($q);
while ($rw = mysql_fetch_assoc($rs))
    fputcsv($fh,$row);
fclose($fh);
?>

 

See the fine manual about fputcsv()

 

Ken

Link to comment
Share on other sites

  • 3 weeks later...

I assume you are referring to a spreadsheet software like Excel? The problem is that a .csv file contains data only, and it cannot store instructions for Excel (or which ever one you use) for cell widths.

 

Only way I can see you doing this is to open the .csv file in your software, adjusting the widths, and saving the file in a different format.

Link to comment
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.