2012-10-15 39 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); 
}