2012-10-15 41 views
0

我正在編寫腳本以編程方式創建Magento屬性,從CSV中提取數據。不知道我有實際的循環是否正確,從CSV中獲取數據 - 希望得到關於邏輯的一些專家指導?從CSV創建屬性作爲循環

<?php 
$fh = fopen("attributes.csv", "r"); 
$i = 0; 
while (($l = fgetcsv($fh, 1024, ",")) !== FALSE) { 

    $i++; 
    if($i == 1) continue; //ignoring the headers, so skip row 0 
    $data['label'] = trim($l[2]); 
    $data['input'] = trim($l[3]); 
    $data['type'] = trim($l[2]); 

    //Create the attribute 

    $data=array(
'type'=>$data['type'], 
'input'=>'text', 
'label'=>$data['label'], 
'global'=>Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL, 
'is_required'=>'0', 
'is_comparable'=>'0', 
'is_searchable'=>'0', 
'is_unique'=>'1', 
'is_configurable'=>'1', 
'use_defined'=>'1' 
); 

$model->addAttribute('catalog_product','test_attribute',$data); 

} 

?> 

我基本上只是希望它抓住從CSV屬性數據,並在CSV每行運行代碼來創建它(使用標籤,如CSV指定的名稱 - 即時猜測我缺少循環的東西明顯?(只是真的學習我在做什麼!)

+0

當你運行這個腳本時會發生什麼?另外,看這篇文章h ttp://alanstorm.com/magento_attribute_migration_generator,它應該有所幫助。 – Zyava

回答

1

重置$data陣列中的每個循環中,將來自CSV的值之後,所以CSV內容會丟失。試試這個

$fh = fopen("attributes.csv", "r"); 
$i = 0; 
$attributes=array(); //!! 
while (($l = fgetcsv($fh, 1024, ",")) !== FALSE) { 

    $i++; 
    if($i == 1) continue; //ignoring the headers, so skip row 0 

    $data=array(); 

    $data['label'] = trim($l[2]); 
    $data['input'] = trim($l[3]); 
    $data['type'] = trim($l[2]); 

    $data['global']=Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL; 
    $data['is_required']='0'; 
    $data['is_comparable']='0'; 
    $data['is_searchable']='0'; 
    $data['is_unique']='1'; 
    $data['is_configurable']='1'; 
    $data['use_defined']='1'; 

    //insert $data to the attributes array 
    $attributes[]=$data; 
    //or 
    $model->addAttribute('catalog_product','test_attribute',$data); 
}