phpcsvexport-to-csvfputcsv

Export CSV with matching header in PHP


I want to export the CSV with the matching header. Please check my data below and see the output what i actually want. I tried but could not find proper solution. Can anyone please help!!!

Header Data,

$headers = array('name', 'sku', 'short_description', 'brand', 'website', 'price', 'url_key', 'weight', 'length');

Array Data :

$data = array(
array('name'=>'Name 1', 'brand'=>'Brand 1', 'url_key'=>'URL key 1', 'length'=>'length 1'),
array('name'=>'Name 2', 'short_description'=>'Shord Description 2', 'sku'=>'SKU 2', 'price'=>'Price2'),
array('name'=>'Name 3', 'sku'=>'SKU 3', 'website'=>'Website 3', 'price'=>'Price 3', 'url_key'=>'URL KEY 3', 'length'=>'Lenght 3'),
array('sku'=>'SKU 4', 'short_description'=>'Short Des 4', 'website'=>'Website 4', 'price'=>'Price4', 'url_key'=>'URL KEY 4')
);

Please see screenshot for required output: enter image description here


Solution

  • Here's a possible implementation:

    // $csvData will be the array that contains the data for our final CSV
    $csvData = [ $headers ]; // adding the headers on the first row
    
    foreach ($data as $row) {
        $csvRow = [];
        foreach ($headers as $header) {
            // checking if the row in the $data array has the value corresponding to the header, if it does not it adds an empty string
            $csvRow[$header] = isset($row[$header]) ? $row[$header] : '';
        }
        $csvData[] = $csvRow;
    }
    
    // creating the CSV
    $outputFile = fopen('output.csv', 'w');
    foreach ($csvData as $csvDataRow) {
        fputcsv($outputFile, $csvDataRow);
    }
    fclose($outputFile);