Search code examples
phpcsvfwrite

PHP Writing Complex Order Info to CSV


I am writing an order exporter in PHP and am having difficulty with php checking a csv header and then writing to a file.

I have my code which opens the file, then writes to the csv

$fh = fopen($file_compile, 'w');

I then write my header:

$header = '"OrderId", "Customer";

foreach ($products as $product) {
  $header .= ', "' . $product . '"';
}

fputs($fh, $header . "\n");

which gives me an output

enter image description here

I now generate my $line array

which outputs:

array(3) {
  ["OrderId"]=>
  string(9) "100000033"
  ["Customer"]=>
  string(14) "Graeme Houston"
  ["total"]=>
  array(3) {
    ["Socks"]=>
    int(12)
    ["Books"]=>
    int(23)
    ["Wallets"]=>
    int(12)
  }
}

Now as you can see, my array doesn't exactly match the CSV above it, which is fine, what I would like to achieve is, if there is a value in the total that matches a value in the header, to but the integer value in the cell. (scratches head)

To illustrate:

enter image description here

I must add I have been trying to figure this out for a few days, I cant get my head round it, hence the post on here. I would be extremely grateful if someone could point me in the right direction.


Solution

  • Not that complex...

    $header = array('OrderId','Customer');
    
    foreach ($products as $product) {
      $header[] = $product;
    }
    
    $tmp = '"' .implode('","',$header) . '"';
    
    fputs($fh, $tmp . "\n");
    

    For your header construction... Then for you line output something similar to:

    foreach($header as $key){
        if(empty($line[$key])) $line[$key] = NULL;
    
        if(empty($line[$key]) && !empty($line['total'][$key])){
             $line[$key] = $line['total'][$key];
        }
    }
    unset($line['total']);
    

    Now you've filled the gaps for non-existent columns, and given values to the existent ones.