What is the fputcsv() Function?

The fputcsv() function is a built-in PHP function that formats an array as a comma-separated values (CSV) line and writes it to a file. This function is used to create CSV files from arrays.

Here's the basic syntax of the fputcsv() function:

fputcsv(file, fields, delimiter, enclosure);

Where file is the file pointer to write to, fields is the array to format as a CSV line, delimiter is the character used to separate fields in the CSV line (default is a comma), and enclosure is the character used to enclose fields in the CSV line (default is a double quote).

How to Use the fputcsv() Function?

Using the fputcsv() function is straightforward. Here are the steps to follow:

  1. Create an array of data to write to the CSV file.
  2. Open the CSV file using the fopen() function in write-only mode.
  3. Call the fputcsv() function, passing in the file pointer, the array of data, and any optional parameters.
  4. Repeat step 3 as needed for additional lines of data.
  5. Close the CSV file using the fclose() function.

Here's an example code snippet that demonstrates how to use the fputcsv() function:

<?php

$data = array(
   array('John', 'Doe', '30', 'Male'),
   array('Jane', 'Doe', '25', 'Female'),
   array('Bob', 'Smith', '40', 'Male')
);
$filename = 'people.csv';
$file = fopen($filename, 'w');
foreach ($data as $line) {
   fputcsv($file, $line);
}
fclose($file);

In this example, we create an array of data to write to a CSV file. We then open the file people.csv using the fopen() function in write-only mode. We loop through the array of data and write each line to the CSV file using the fputcsv() function. Finally, we close the CSV file using the fclose() function.

Conclusion

The fputcsv() function is a useful tool in PHP for creating CSV files from arrays. By following the steps outlined in this guide, you can easily use the fputcsv() function in your PHP projects to write data to CSV files.

Practice Your Knowledge

What is the use of the fputcsv() function in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?