chronister Posted July 4, 2007 Share Posted July 4, 2007 Hey Folks, I need some assistance with fwrite. Trying to take some customer data, and export it as a csv. Doing it manually and here is my code. <?php connectdb(); $query="SELECT * FROM customers ORDER BY lname"; $result=mysql_query($query) or die(mysql_error()); while($row=mysql_fetch_object($result)) { $customer='"'.$row->fname.'","'.$row->lname.'","'.$row->address.'","'.$row->city.'","'.$row->state.'","'.$row->zip.'","'.$row->phone.'","'.$row->email.'" \r\n'; if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } // Write $somecontent to our opened file. if (fwrite($handle, $customer) === FALSE) { echo "Cannot write to file ($filename)"; exit; } $x++; fclose($handle); } echo 'Exported '. $x .'Customers'; ?> The problem is that I cannot write each customer record to a new line. It writes all customer data on one line. How do I get a new line to be created each time? Quote Link to comment Share on other sites More sharing options...
Barand Posted July 4, 2007 Share Posted July 4, 2007 You can use MySQL SELECT... INTO OUTFILE to write directly to a csv with a single query http://dev.mysql.com/doc/refman/4.1/en/select.html Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted July 4, 2007 Share Posted July 4, 2007 Escape characters can only be used within double quotes. I'd change this line: $customer='"'.$row->fname.'","'.$row->lname.'","'.$row->address.'","'.$row->city.'","'.$row->state.'","'.$row->zip.'","'.$row->phone.'","'.$row->email.'" \r\n'; To this: $customer='"'.$row->fname.'","'.$row->lname.'","'.$row->address.'","'.$row->city.'","'.$row->state.'","'.$row->zip.'","'.$row->phone.'","'.$row->email.'"'; And change this line: if (fwrite($handle, $customer) === FALSE) { to this: if (fwrite($handle, $customer . "\r\n")=== FALSE) { EDIT: Brand beat me. I'd recommend Brands suggestion. Quote Link to comment Share on other sites More sharing options...
chronister Posted July 5, 2007 Author Share Posted July 5, 2007 You can use MySQL SELECT... INTO OUTFILE to write directly to a csv with a single query http://dev.mysql.com/doc/refman/4.1/en/select.html That worked beautifully on my home machine, but I get permission denied when I do it on my real server. I had found that first, did not work so I am trying it the hard way. The other suggestion worked perfectly. I removed the /r/n and added it in the fwrite. Combined it with a second script and it forces the download of the properly formatted .csv file. Thanks Guys!! Nate Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.