Do you know which fields are being written? In MySQL at least you can get a resultset containing a table's field names using mysql_list_fields()
http://www.php.net/mysql_list_fields
You can build up an $array of the fields you want represented and then go $firstline=join('|',$array) to provide you with the first line. Oh, and a $firstline.="|\n"; to get that last | and a newline.
Then you proceed to write the rest of the file.