I found this great library to handle the whole thing:
http://blog.leenix.co.uk/2009/04/lightweight-php -class-to-export-to.html
This creates an xls file, rather than a csv. A CSV file can be opened by excel, but in some cases a csv is preferable because it can be used by other scripts or loaded to a database, etc.