Magento のコピー用の PHP エクスポート スクリプトを作成しています。何らかの理由で、次のコードで「ヘッダーは既に送信されました」というエラーが表示されます。
//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;
}
}
ここで問題を引き起こしているコード行は次のとおりですfputcsv($fp, $headerRow);
。何らかの理由で、この行がコメントアウトされていると、スクリプトは正常に実行されます。ただし、この行をスクリプトで実行すると、header already sent エラーが発生します。foreach ループ内で何度でも fputcsv を実行できる理由がわかりませんが ( fputcsv($fp, $row);
)、foreach ループの前に実行することはまったくできません。
私はこの問題を回避する方法を持っているので、それほど重要ではありませんが、何が原因でこの問題が発生したのかを理解できれば幸いです.
御時間ありがとうございます!