You can import and export CSV (Comma-Separated Values) files using PHP by reading from and writing to CSV files. Below, I’ll provide you with simple examples for both importing and exporting CSV data.

Export Data to CSV:

// Sample data
$data = array(
    array('Name', 'Email', 'Phone'),
    array('John Doe', '', '555-123-4567'),
    array('Jane Smith', '', '555-987-6543'),
    // Add more data as needed

// File name for exporting data
$filename = 'exported_data.csv';

// Create and open the CSV file for writing
$file = fopen($filename, 'w');

// Write data to the CSV file
foreach ($data as $row) {
    fputcsv($file, $row);

// Close the CSV file

// Download the CSV file
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '"');

In this code, we first define the data you want to export as a 2D array. Then, we create a CSV file named ‘exported_data.csv’, write the data to it using the fputcsv function, and finally send the CSV file to the user for download.

Import Data from CSV:

Assuming you have a CSV file named ‘imported_data.csv’ with data you want to import:

$filename = 'imported_data.csv';

// Check if the file exists
if (file_exists($filename)) {
    // Open the CSV file for reading
    $file = fopen($filename, 'r');

    // Initialize an array to store imported data
    $importedData = array();

    // Read and process each row in the CSV file
    while (($row = fgetcsv($file)) !== false) {
        $importedData[] = $row;

    // Close the CSV file

    // Display the imported data
    echo '<pre>';
    echo '</pre>';
} else {
    echo 'The CSV file does not exist.';

In this code, we open the ‘imported_data.csv’ file for reading, read its content row by row using fgetcsv, and store the data in the $importedData array. You can then process and use this data as needed in your PHP application.

Make sure to adapt these examples to your specific use case, including handling any data validation, manipulation, or database interaction required for your application.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *