PDA

View Full Version : How to create a tab delimited text file from a database??


tux
03-03-2009, 10:34 PM
Hello All,

Is it possible to create a Tab Delimited Text File from my MYSQL database using PHP.

I want my client to be able to create this file using a CMS on his website so he can use it to import the info into a mailing list application like 'Mail Chimp'.

Anyone know if this is possible. Thanks.

Paul

davidj
03-04-2009, 05:46 AM
fwrite will do this


$wfile= fopen('file.txt', 'a');

while(){ //<< loop here

fwrite($wfile, $row['field1']."|".$row['field2']."|".$row['field3']."\n");

}

fclose($wfile);

tux
03-04-2009, 06:01 AM
Nice to hear from you again Dj, been a while since I've been about.

Thanks for that I will give it a try.

How do I actually output the file. Is it possible to have a save as dialogue pop up or maybe save it on the server and create a link to it.

Cheers mate,

Paul

davidj
03-04-2009, 07:18 AM
you can name the file anything you want and have a link to it

username.txt for example

In my example i use a pipe to delimit. If you use a comma and the extension of csv it will open in excel without to much trouble

tux
03-04-2009, 10:29 AM
Ok David,

I've had a bit of a play and have come up with this....

<?php
require_once("MY CONNECTION SCRIPT"); // database connection
///////////////////////////////////////////
$query = sprintf("SELECT * FROM mail_list ");
$result = @mysql_query($query);
$mail_list = @mysql_fetch_array($result);

//echo $mail_list['email'];
///////////////////////////////////////////
$wfile= fopen('mail_list.txt', 'a');

do{

fwrite($wfile, $mail_list['email']." ".$mail_list['first_name']." ".$mail_list['last_name']."\n");

}

while ($mail_list = @mysql_fetch_array($result));

fclose($wfile);
?>

... it works ok but each row from the DB prints to file on the same line and not on one line each.

Also, I need it to over write the file and not add to it each time the script is run. Can you give me some more pointers. Cheers,

Paul

davidj
03-04-2009, 12:51 PM
not sure why its writing to the same line as we have a \n control in there

is it taking the \n as literal and writing that to file also?

could try \n\r\cr

change the alpha in here

$wfile= fopen('mail_list.txt', 'a');

from an a to a w

a = append
w = write

tux
03-04-2009, 09:13 PM
Changing to a w has worked but still cant get the rows to print to a new line.

Its not writing the \n literally.

Changing the \n to \n\r\cr is just adding the \cr part to the line between rows.

Any ideas!!

davidj
03-05-2009, 06:18 AM
///////////////////////////////////////////

$query = sprintf("SELECT * FROM table1 ");

$result = mysql_query($query);

///////////////////////////////////////////


$wfile= fopen('mail_list.txt', 'w');

while($row = @mysql_fetch_array($result)){

$lines .= $row['field2']." ".$row['field3']." ".$row['field4']."\r\n";

}

fwrite($wfile, $lines);

fclose($wfile);