How can you create a CSV file using PHP?Answer
How can you create a CSV file using PHP?Answer
To create a CSV file using PHP, you can follow these steps:
- Open a file using the
fopen()
function and specify the mode asw
to write to the file. - Write the CSV header row, if necessary, using the
fputcsv()
function. - Loop through your data and write each row to the file using the
fputcsv()
function. - Close the file using the
fclose()
function.
Here's an example code snippet that demonstrates how to create a CSV file in PHP:
// Specify the file name and mode $filename = 'data.csv'; $file = fopen($filename, 'w'); // Write the CSV header row $header = array('Name', 'Age', 'Email'); fputcsv($file, $header); // Loop through the data and write each row to the file $data = array( array('John', 30, 'john@example.com'), array('Jane', 25, 'jane@example.com'), array('Bob', 35, 'bob@example.com') ); foreach ($data as $row) { fputcsv($file, $row); } // Close the file fclose($file);
Comments
Post a Comment