Page 1 of 1
How to prepare csv file in php?
Posted: Mon Dec 06, 2010 6:36 am
by ramyabeena
Code: Select all
$fp=fopen($file,w);
$heading="E - Mail,First Name,Last Name,Company Name,Address1,Address2,City,State,Country,Zip Code,Website,Phone,Title,Title Level"."\n";
fwrite($fp,$heading);
$selected = explode('a', $ids);
for($i=0;$i<(count($selected)-1);$i++)
{
if($selected[$i]!="")
{
$sel_query2 = mysql_query("select email from cart where id='".$selected[$i]."'");
while($row2 = mysql_fetch_assoc($sel_query2))
{
$email=$row2["email"];
$sel_query1 = mysql_query("select * from contacts where email='".$email."'");
while($row1 = mysql_fetch_assoc($sel_query1))
{
$data=$row1["email"].','.$row1["fname"].','.$row1["lname"].','.$row1["cname"].','.trim($row1["cadd1"]).','.trim($row1["cadd2"]).','.$row1["city"].','. $row1["state"].','. $row1["ctry"].','.$row1["zip"].','. $row1["web"].','. $row["phone"].','.$row1["title"].','.$row1["level"]."\n";
fwrite($fp,$data);
}
}
}
}
fclose($fp);
$f=$fn.".csv";
The above code was working properly, but the problem is when i opened a file, if the data contains comma(,) then if i opened in excel sheet, it was not in correct format. I dont know what to do. Please help me to do it in correct format.
Thanks in advance
Re: How to prepare csv file in php?
Posted: Mon Dec 06, 2010 7:06 am
by awebtech
Hi, you can use the
fputcsv function (
http://ru2.php.net/manual/en/function.fputcsv.php).
Then you can do not care about correct CSV syntax. All you need to so is to provide the array with field values.
PS: this function work only in PHP 5 >= 5.1.0
Re: How to prepare csv file in php?
Posted: Mon Dec 06, 2010 8:46 am
by awebtech
Actually, I could not resist to rewrite the code more concise, but I didn't test it
Code: Select all
$fp = fopen($file, w);
$heading = array('E - Mail', 'First Name', 'Last Name', 'Company Name', 'Address1', 'Address2', 'City', 'State',
'Country', 'Zip Code', 'Website', 'Phone', 'Title', 'Title Level');
fputcsv($fp, $heading);
$selected = explode('a', $ids);
$sql = "
SELECT
c.email, c.fname, c.lname, c.cname, TRIM(c.cadd1), TRIM(c.cadd2),
c.city, c.state, c.ctry, c.zip, c.web, c.phone, c.title, c.level
FROM
contacts AS c
INNER JOIN
cart ON
cart.email = c.email
WHERE
cart.id IN ('".implode(', ', $selected)."')
";
$mres = mysql_query($sql);
while ($row = mysql_fetch_row($mres)) {
fputcsv($fp, $row);
}
fclose($fp);
$f = $fn.".csv";