以下代码应该将 4 个字段输出到 CSV 中Category, SKU, Price and Special Price
,并且在大多数情况下运行良好,除了输出在所有项目周围都有 3 个引号,如下所示
"""Joystick Head""","""Man222""","""155""","""124.95"""
但是浏览器中的输出很好
Type: "Joystick Head" SKU: "Man222" Price: "155" Special Price: "124.95"
我已经尝试过str_replace
,implode
以及我能想到的任何其他方法,结果各不相同,有时设法删除了几乎所有的引号。
我希望这是愚蠢的,我已经盯着它太久了,帮助?
define('SAVE_FEED_LOCATION','var/export/prices.csv');
set_time_limit(0);
require_once 'app/Mage.php';
Mage::app('default');
try{
$handle = fopen(SAVE_FEED_LOCATION, 'w');
$attributeName = 'producttype';
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('visibility', 4);
$products->addAttributeToSelect('*');
$prodIds = $products->getAllIds();
$product = Mage::getModel('catalog/product');
$counter_test = 0;
foreach($prodIds as $productId) {
if (++$counter_test > 0 && $counter_test < 100){
$product->load($productId);
$product_data = array();
$productId = $product->getId();
$productAtt = Mage::getModel('catalog/product')->load($productId);
$attributes = $productAtt->getAttributes();
$attributeValue = null;
if(array_key_exists($attributeName , $attributes)){
$attributesobj = $attributes["{$attributeName}"];
$attributeValue = $attributesobj->getFrontend()->getValue($productAtt);
}
if ($attributeValue == "No")
{
$attributeValue = NULL;
}
$product_data['producttype'] = $attributeValue;
$product_data['sku'] = $product->getSku();
$product_data['price'] = round($product->getPrice(),2);
$product_data['special_price'] = round($product->getSpecialprice(),2);
// if no special price use normal price
if ($product_data['special_price'] == NULL) {
$product_data['special_price'] = round($product->getPrice(),2);
}
foreach($product_data as $k=>$val){
$bad=array('"',"\r\n","\n","\r","\t");
$good=array(""," "," "," ","");
$product_data[$k] = '"'.str_replace($bad,$good,$val).'"';
}
echo "Type: ". $product_data['producttype'] . " SKU: " . $product_data['sku'] . " Price: ". $product_data['price'] . " Special Price: " . $product_data['special_price'] . "<br>";
fputcsv($handle, $product_data, ',', '"');
}
}
fclose($handle);
echo '<br> Completed at: ' . time();
}
catch(Exception $e){
$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
error_log($e->getMessage(), 1, 'myemail@mydomain.com', $headers);
die($e->getMessage());
}