PHP Function fputcsv
CSV files play an important role in data interchange between different systems and are used extensively in web applications. To ease the process of creating and reading such files, PHP provides a built-in function called fputcsv. This article will provide a detailed walkthrough of this function and show you how to use it in your application.
fputcsv() formats a line (passed as a fields array) as a Comma Separated Values line and writes it to an open file stream. The file pointer must be valid, and must point to a file successfully opened by fopen() or popen() or fsockopen() (and not yet closed by fclose()). The optional delimiter parameter sets the field delimiter (one character only), the optional enclosure parameter sets the field enclosure (one character only), and the optional escape_char parameter sets the escape character. The return value is the length of the written string on success, or FALSE on failure.
This function is useful for writing data into a CSV file, especially when you have multiple values to write to each row in the file. It also comes in handy when you need to quickly create a CSV file and then read it back into your database, or when you want to print out the data from a CSV file to the web browser.
Note: If you are using fputcsv() to write data to a CSV file and your field contains an enclosure character that is not escaped by the escape_char parameter, then you will need to enable the auto_detect_line_endings run-time configuration option in PHP. This will help resolve a problem with PHP not properly recognizing line endings when reading files either on or created by a Macintosh computer.