Jump to content

[SOLVED] help with fwrite


chronister

Recommended Posts

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?

 

Link to comment
https://forums.phpfreaks.com/topic/58453-solved-help-with-fwrite/
Share on other sites

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.

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.