Force fputcsv to enclose output in quotes

1.3k views Asked by At

I found a couple of topics online about forcing to enclose the fputcsv output and found out that's not possible to do this. I need to enclose every output with quotes, because of some import requirements. Seperate words are working, but non-seperate works are not. I saw that there are a couple of workarounds, but I can't get them working. For example, I have this code:

/**
 * Writes the row(s) for the given order in the csv file.
 * A row is added to the csv file for each ordered item. 
 * 
 * @param Mage_Sales_Model_Order $order The order to write csv of
 * @param $fp The file handle of the csv file
 */
protected function writeOrder($order, $fp) 
{
    $common = $this->getCommonOrderValues($order);
    $orderItems = $order->getItemsCollection();
    $itemInc = 0;
    foreach ($orderItems as $item)
    {
        if (!$item->isDummy()) {
            $record = array_merge($common, $this->getOrderItemValues($item, $order, ++$itemInc));
            fputcsv($fp, $record, self::DELIMITER, self::ENCLOSURE);
        }
    }
}

Can you help me out to get this working?

1

There are 1 answers

5
kguest On

Use the File_CSV package from PEAR at https://pear.php.net/package/File_CSV/

Your code would look something like this, which is obviously incomplete:

<?php
require 'File/CSV.php'; 
$csv_conf = array(
    'fields' => 3, 
    'crlf' => "\r\n", 
    'quote' => '"', 
    'sep' => ','
);

$common = $this->getCommonOrderValues($order);
$orderItems = $order->getItemsCollection();
$itemInc = 0;
foreach($orderItems as $item) {
    if (!$item->isDummy()) {
        $record = array_merge(
            $common, 
            $this->getOrderItemValues($item, $order, ++$itemInc)
        );
        $res = File_CSV::write($fileName, $record, $csv_conf);
    }
}