What is the purpose of using fputcsv() function in PHP?
The fputcsv() function in PHP is used to write an array to a file in CSV format. This function automatically formats the array data into a comma-separated line and writes it to the specified file pointer. This is useful for generating CSV files for data export or manipulation.
// Open a file for writing
$fp = fopen('data.csv', 'w');
// Array of data to write to the CSV file
$data = array(
array('John', 'Doe', 30),
array('Jane', 'Smith', 25),
array('Bob', 'Johnson', 35)
);
// Write the data to the CSV file
foreach ($data as $row) {
fputcsv($fp, $row);
}
// Close the file pointer
fclose($fp);
Keywords
Related Questions
- How can multiple simultaneous requests for the same PHP script that generates a PNG image be handled to prevent conflicts?
- What are the potential pitfalls of not properly checking the length of a string in PHP?
- In terms of PHP security, what methods can be used to protect the upload directory and ensure that files are not directly accessible through the browser, such as using .htaccess files or server-side script handling?