What is the correct usage of file_put_contents in PHP when exporting data to a CSV file?
When using file_put_contents to export data to a CSV file in PHP, it is important to properly format the data as a comma-separated string before writing it to the file. This can be achieved by using the implode function to join the data array elements with commas. Additionally, make sure to include the newline character "\n" at the end of each row to separate the rows in the CSV file.
$data = array(
array('John', 'Doe', 'john.doe@example.com'),
array('Jane', 'Smith', 'jane.smith@example.com'),
);
$csv = '';
foreach ($data as $row) {
$csv .= implode(',', $row) . "\n";
}
file_put_contents('export.csv', $csv);
Keywords
Related Questions
- How can a WWW-Authenticate with NTLM be implemented in PHP?
- How can XAMPP and live server environments differ in handling PHP scripts, such as displaying a "Server not found" error when navigating back using the browser?
- What are the implications of using xy coordinates from pressed buttons in PHP forms, as seen in the provided code snippet?