I am writing a PHP export script for my copy of magento. For some reason, the following code gives me a "Headers already sent" error:
//Load magento and set to match frontend
require_once '../../app/Mage.php';
umask(0);
Mage::app();
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
//Send headers to browser to prep for csv file download
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exportSKUs.csv');
//Load only product collection details that we need.
$product = Mage::getModel('catalog/product');
$product->getCollection()->getSelect()->limit(5);
$products = $product->getCollection()
->addFieldToFilter('status','1')
->addAttributeToSelect('name')
->addAttributeToSelect('sku')
->addAttributeToSelect('upc')
->addAttributeToSelect('status')
->addAttributeToSelect('price')
->addAttributeToSelect('special_price')
->addAttributeToSelect('description')
->addAttributeToSelect('category_ids')
->addAttributeToSelect('short_description');
//Open current output to fputcsv
$fp = fopen('php://output', 'w');
//CSV headers
$headerRow = array(
'name',
'sku',
'upc',
'status',
'price',
'special_price',
'description',
'category_ids',
'short_description'
);
fputcsv($fp, $headerRow);
$count = 0;
//CSV Rows
foreach($products as &$product){
$categoryIds = implode(',', $product->getCategoryIds());
$row = array(
$product->getName(),
$product->getSku(),
$product->getUpc(),
$product->getStatus(),
$product->getPrice(),
$product->getSpecialPrice(),
$product->getDescription(),
$categoryIds,
$product->getShortDescription()
);
fputcsv($fp, $row);
$count++;
if($count>5){
//Close current output (save csv)
fclose($fp);
exit;
}
}
The line of code here that is causing me problems is this: fputcsv($fp, $headerRow);
For some reason, when this line is commented out the script runs fine. However, when this line is run with the script, it shoots the header already sent error. I don't understand why I am able to run fputcsv INSIDE my foreach loop any number of times (fputcsv($fp, $row);
)but I can not run it before the foreach loop at all.
I have ways around this issue, so it's not super critical, but I really wish I could understand what was going on here to cause this.
Thanks for your time!