Forum Moderators: coopster

Message Too Old, No Replies

PHP Create CSV with values encapsulated in double quotes

PHP Create CSV with values encapsulated in double quotes

         

razn8

8:59 am on Feb 20, 2009 (gmt 0)

10+ Year Member



I process a form, insert to mysql with php, then append the form data to a csv. The client needs the csv values encapsulated in double quotes;

"value1","value2","value3",...

I'm having difficulty figuring this out. I've tried several different methods, to no avail. Heres my code:

//saving record in a csv file
$file_name = "form.csv";
$first_row = "Process,VendorID,Type,Null1,FirstName,LastName,Null2\r\n";
$values = "Process,VendorID,Type,null,FirstName,LastName,null\r\n";
$is_first_row = false;
if(!file_exists($file_name))
{
$is_first_row = true ;
}
if (!$handle = fopen($file_name, 'a+')) {
die("Cannot open file ($file_name)");
exit;
}
if ($is_first_row)
{
if (fwrite($handle, $first_row ) === FALSE) {
die("Cannot write to file ($filename)");
exit;
}
}
if (fwrite($handle, $values) === FALSE) {
die("Cannot write to file ($filename)");
exit;
}
fclose($handle);

supermanjnk

8:02 pm on Feb 20, 2009 (gmt 0)

10+ Year Member



When I create a CSV file with the following:
"value1" "value2" "value3"
and then open it in notepad I get the following:

"""value1""","""value2""","""value3"""

Hope this helps.

IanKelley

8:14 pm on Feb 20, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Maybe I'm not understanding what you're trying to accomplish, why not replace this:
$values = "Process,VendorID,Type,null,FirstName,LastName,null\r\n";

With this:

$values = '"Process","VendorID","Type","null","FirstName","LastName","null"'."\r\n";

BTW you do not need to open the file with in "a+" mode as you are not reading from it. Use "a" mode instead.

razn8

12:51 pm on Feb 21, 2009 (gmt 0)

10+ Year Member



IanKelley,
Thanks, that works as described. But it doesn't work for stored values?

e.g.:
---
$values = '"Process","VendorID","Type","null","$FirstName","$LastName","null"'."\r\n";
---

$FirstName and $LastName should read: "John","Doe", with values posted from the html form or selected from mysql. Instead, they just read "$FirstName","$LastName"

IanKelley

3:20 pm on Feb 21, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



That's because strings encapsulated in single quotes are not parsed for variables. There are a few ways to do what you're after, here's one:

$values = '"'.$Process.'","'.$VendorID.'","'.$Type.'","'.$null.'","'.$FirstName.'","'.$LastName.'","'.$null"'."\r\n";

razn8

6:16 pm on Feb 21, 2009 (gmt 0)

10+ Year Member



Thanks!:)