0

I figure out how to write all the entries from my database onto a text file.

header("Content-Type: text/plain");
header("Content-Disposition: Attachment; filename=test.txt");
header("Pragma: no-cache");
exit;

How do I modify the text file??
Each entries (or row) have 5 elements in it and there are multiple entries in my database.
How do I write each elements follow by a comma onto a text file? Each row in the database would have a new line in my text file as well.

tks

4
Contributors
5
Replies
6
Views
5 Years
Discussion Span
Last Post by LastMitch
0

I use fwrite to write onto a text file
But how do I know that I'm done with each entries when I'm writing to a text file, so I can separte them with a comma because each entries can have more then one word in it

SQL Entries:
Name | Age | Country
John Adam Smith | 37 | USA
Steve Jones | 22 | Canada
Marie Eve Thomas Faucher | 19 | Canada

Also, how do I know when I reach the end of the row, so I can add in a new line.

1

PHP has built in functions to handle this case. They are called fgetcsv and fputcsv.

You can read the textfile into an array using fgetcsv and write the changed values back using fputcsv. These functions handles both the field delimiter (comma or semi-colon), string enclosures (the " or ') and the escape character (the backslash).

Nice samples are included in the php.net manual.

0

There are many ways to acheive this, but it's best if you work this out yourself (teach a man to fish.)

<?php
$arr = array();
//make data connection and send query
while ($row = mysql_fetch_assoc($res)){//loop through all db rows
    $arr[] = $row['Name'].", ".$row['Age'].", ".$row['Country']."\n"; 
    //store each line in the array called $arr.
    }
//open the file ready for writing
//now loop through and write each line to file.
foreach($arr as $k => $v){
    //write $v to file
}
//close the file.
?>
0

@hiyatran

How do I modify the text file??
Each entries (or row) have 5 elements in it and there are multiple entries in my database.
How do I write each elements follow by a comma onto a text file? Each row in the database would have a new line in my text file as well.

You can try this

$i=0;
foreach(file("test.txt") as $key => $value) {
   if($tempfile=explode(",",$value)) {
     if(@mysql_query("UPDATE test_table SET ".$tempfile[1]."='".$tempfile[0]."';")) {
       $i++;
     }
   }
}
if($i==sizeof(file("test.txt")) echo "Writing.";
else echo "Try Again!";
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.