Eg:the csv have two columns. The structure is : it only have the header.
sku name
Now, there is a foreach loop:
foreach ($collection as $product_all)
{
$sku = $product_all['sku'];
$product_id = Mage::getModel('catalog/product')->getIdBySku($sku);
$product = Mage::getModel('catalog/product');
$product ->load($product_id);
$name = $product['name'];
}
I want to put the $sku and the $name into the csv file, if there is 8000 rows lines. How do I do? I using the following code. But it doesn’t work. How to correct it? Thank you.
foreach ($collection as $product_all)
{
$sku = $product_all['sku'];
$product_id = Mage::getModel('catalog/product')->getIdBySku($sku);
$product = Mage::getModel('catalog/product');
$product ->load($product_id);
$name = $product['name'];
$newCsvData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$data[0] = $sku;
$data[2] = $name;
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('test.csv', 'w');
foreach ($newCsvData as $line)
{
fputcsv($handle, $line);
}
fclose($handle);
}
Did not try it, but it should work.
The
fputcsvfunction takes care of all escaping for you, which is no small job if you want your csv file to work across any input.After reading some comments on other answers, you could move the
fputcsvcall in the loop: