За последние 24 часа нас посетили 52534 программиста и 1797 роботов. Сейчас ищут 814 программистов ...

Нужно поправить говнокод экспорта .CSV

Тема в разделе "PHP для новичков", создана пользователем Invision, 25 апр 2011.

  1. Invision

    Invision Активный пользователь

    С нами с:
    26 фев 2009
    Сообщения:
    1.437
    Симпатии:
    1
    Адрес:
    Томск
    Вообщем есть говноцмс WebAsyst Shop у нее есть экспорт товаров. Клиенту нужно получить только:

    PHP:
    1.         'name' => "Имя", // Имя
    2.         'in_stock' => "Склад", // На складе
    3.         'Optprice_firm' => "Опт", // Оптовая цена
    4.         'Price' => "Розница", // Розничная цена
    5.         'Price_firm' => "Закуп", // Закупочная цена
    Вот кусок говноэкспорта:

    PHP:
    1. <?php
    2. global $picture_columns_count;
    3. global $extra_columns_count;
    4. /* @vars $smarty Smarty */
    5. $smarty = &Core::getSmarty();
    6.  
    7. function __exportProducts()
    8. {
    9.     $exportData = ClassManager::getInstance('ExportData');
    10.     /*@var $exportData ExportData*/
    11.     $whereClause = '';
    12.     $exportData->sqlWhereClause = $whereClause;
    13.        
    14.     $orderClause = "";
    15.     $exportData->sqlOrderClause = $orderClause;
    16.        
    17.     $exportData->charset = $_GET['charset'];
    18.     $exportData->setHeaders(array_map('translate',
    19.     array('')));
    20.     $exportData->sqlQuery = '';
    21.        
    22.        
    23.        
    24.     //$exportData->setRowHandler('foreach($row as $key=>&$value){$value = "[{$key}]{$value}";}');
    25.     //  $exportData->setRowHandler('$row[\'orderID\'] = {$value = "[{$key}]{$value}";}');
    26.     $exportData->setRowHandler('$row[\'order_time\'] = Time::standartTime($row[\'order_time\']);return $row;');
    27.        
    28.        
    29.     //$exportData->fileName = DIR_TEMP.'/orders.csv';
    30.        
    31.     $time = microtime(true);
    32.     $res = $exportData->exportDataToFile(DIR_TEMP.'/orders.csv');
    33. }
    34.  
    35. function _exportCategoryLine($categoryID, $level, &$f, $delimiter = ";"){ //writes a category line into CSV file.
    36.  
    37.     global $picture_columns_count;
    38.     global $extra_columns_count;
    39.  
    40.     //$defaultLanguage = &LanguagesManager::getDefaultLanguage();
    41.  
    42.     $q = db_phquery("SELECT * FROM ?#CATEGORIES_TABLE WHERE categoryID=?", $categoryID);
    43.     $cat_data = db_fetch_row($q);
    44.     if (!$cat_data) return;
    45.  
    46.     $lev = "";
    47.     $lang_name_fields = LanguagesManager::ml_getLangFieldNames('name');
    48.     for ($i=0;$i<$level;$i++) $lev .= "!";
    49.     foreach($lang_name_fields as $lang_name_field){
    50.         $cat_data[$lang_name_field] = $lev.$cat_data[$lang_name_field];
    51.     }
    52.  
    53.     $data = array();
    54.     $product_fields = _getProductFields();
    55.     if(!isset($cat_data['slug'])||!$cat_data['slug']){
    56.         $cat_data['slug'] = $cat_data['categoryID'];
    57.     }
    58.     foreach ($product_fields as $_k=>$_t){
    59.  
    60.         $data[$_k] = '';
    61.         if(!isset($cat_data[$_k]))continue;
    62.  
    63.         $data[$_k] = $cat_data[$_k];
    64.         if (strstr($data[$_k],"\"") || strstr($data[$_k],"\n") || strstr($data[$_k],$delimiter)){
    65.                
    66.             $data[$_k] = '"'.str_replace('"','""', str_replace("\r\n"," ",$data[$_k]) ).'"';
    67.         }
    68.     }
    69.     fputs($f, implode($delimiter, $data));
    70.  
    71.     for ($i=1;$i<$picture_columns_count+$extra_columns_count;$i++)fputs($f,$delimiter);
    72.  
    73.     fputs($f,"\n");
    74. }
    75.  
    76. function _exportProducts($categoryID, &$f, $delimiter = ";") //writes all products inside a single category to a CSV file
    77. {
    78.     global $picture_columns_count;
    79.     global $extra_columns_count;
    80.  
    81.     $defaultLanguage = &LanguagesManager::getDefaultLanguage();
    82.     $product_fields = _getProductFields();
    83.     $option_fields = _getOptionFields();
    84.     //products
    85.     $q1 = db_phquery('SELECT *, '.LanguagesManager::sql_constractSortField(PRODUCTS_TABLE, 'name').' FROM ?#PRODUCTS_TABLE WHERE categoryID=? ORDER BY sort_order, '.LanguagesManager::sql_getSortField(PRODUCTS_TABLE, 'name'), $categoryID);
    86.     while ($row1 = db_fetch_assoc($q1)){
    87.        
    88.         if(!isset($row1['slug'])||!$row1['slug']){
    89.             $row1['slug'] = $row1['productID'];
    90.         }
    91.         $row1['invisible'] = (isset($row1['enabled'])&&!$row1['enabled'])?"1":"";
    92.  
    93.         $data = array();
    94.         foreach($product_fields as $_k=>$_v){
    95.                        
    96.             $data[$_k] = '';
    97.  
    98.             if(!isset($row1[$_k])||$_k=='picture')continue;
    99.             $data[$_k] = $row1[$_k];
    100.             if (strstr($data[$_k],"\"") || strstr($data[$_k],"\n") || strstr($data[$_k],$delimiter)){
    101.                 $data[$_k] = '"'.str_replace('"','""',str_replace("\r\n"," ",$data[$_k])).'"';
    102.             }
    103.             if (!strcmp($_k,"Price") || !strcmp($_k,"list_price")){
    104.  
    105.                 $data[$_k] = round(100*$data[$_k])/100;
    106.                 if (round($data[$_k]*10) == $data[$_k]*10 && round($data[$_k])!=$data[$_k])
    107.                 $data[$_k] = (string)$data[$_k]."0"; //to avoid prices like 17.5 - write 17.50 instead
    108.             }
    109.             if($_k == 'classID'){
    110.                 $class = taxGetTaxClassById($data[$_k]);
    111.                 $data[$_k] = $class['name'];
    112.             }
    113.             if($_k == 'product_code'){
    114.                 $data[$_k] = '"'.$data[$_k].'"';
    115.             }
    116.         }
    117.  
    118.         //write primary product information
    119.         fputs($f, implode($delimiter, $data));
    120.  
    121.         //pictures
    122.         //at first, fetch default picture
    123.         $cnt = 0;
    124.         if (!$row1["default_picture"]) $row1["default_picture"] = 0; //no default picture defined;
    125.         $qp = db_query("select filename, thumbnail, enlarged from ".PRODUCT_PICTURES." where productID=".$row1["productID"]." and photoID=".$row1["default_picture"]);
    126.         $rowp = db_fetch_row($qp);
    127.         $s = "";
    128.         if ($rowp)
    129.         {
    130.             if ($rowp[0]) $s .= $rowp[0];
    131.             if ($rowp[1]) $s .= ",".$rowp[1];
    132.             if ($rowp[2]) $s .= ",".$rowp[2];
    133.         }
    134.         fputs($f,$delimiter.'"'.str_replace('"','""',str_replace("\r\n"," ",$s)).'"');
    135.         $cnt++;
    136.         /**
    137.          * @features "Multiple image-sets for product"
    138.          * @state begin
    139.          */
    140.         //the rest of the photos
    141.         $qp = db_query("select filename, thumbnail, enlarged from ".PRODUCT_PICTURES." where productID=".$row1["productID"]." and photoID <> ".$row1["default_picture"].' ORDER BY priority');
    142.         while ($rowp = db_fetch_row($qp))
    143.         {
    144.             $s = "";
    145.             if ($rowp)
    146.             {
    147.                 if ($rowp[0]) $s .= $rowp[0];
    148.                 if ($rowp[1]) $s .= ",".$rowp[1];
    149.                 if ($rowp[2]) $s .= ",".$rowp[2];
    150.             }
    151.             fputs($f,$delimiter.'"'.str_replace('"','""',str_replace("\r\n"," ",$s)).'"');
    152.             $cnt++;
    153.         }
    154.  
    155.         if ($cnt < $picture_columns_count)
    156.         for ($i=$cnt; $i<$picture_columns_count; $i++) fputs($f,$delimiter);
    157.         /**
    158.          * @features "Multiple image-sets for product"
    159.          * @state end
    160.          */
    161.  
    162.  
    163.         //extra options
    164.         $q2 = db_query("select optionID, ".LanguagesManager::sql_constractSortField(PRODUCT_OPTIONS_TABLE, 'name')." from ".PRODUCT_OPTIONS_TABLE." ORDER BY sort_order, ".LanguagesManager::sql_getSortField(PRODUCT_OPTIONS_TABLE, 'name'));
    165.         //browse options list
    166.  
    167.         $option_values = array();
    168.         while ($row2 = db_fetch_assoc($q2)){
    169.                
    170.             //browser all option values of current product
    171.             $q3 = db_query("select * from ".PRODUCT_OPTIONS_VALUES_TABLE." where productID=".$row1['productID']." and optionID=".$row2['optionID']);
    172.             //          $q3 = db_query("select option_value, option_type, variantID from ".PRODUCT_OPTIONS_VALUES_TABLE." where productID=".$row1['productID']." and optionID=$row2[0]");
    173.             $row3 = db_fetch_assoc($q3);
    174.             if(!$row3) $row3 = array('optionID' => 0, 'option_type' => 0, 'variantID' => 0);
    175.                
    176.             /*
    177.              @features "Extra options values"
    178.              @state begin
    179.              */
    180.             if ((int)$row3['option_type'] == 1){ //selectable option - prepare a string to insert into a CSV file, e.g {red=3,blue=1,white}
    181.  
    182.                 //prepare an array of available option variantIDs. the first element (0'th) is the default varinatID
    183.                 $available_variants = array();
    184.                 $available_variants[] = array('variantID'=>$row3['variantID']);
    185.  
    186.                 $q4 = db_query( "select variantID, price_surplus from ".PRODUCTS_OPTIONS_SET_TABLE." where productID=".$row1['productID']." and optionID=".$row2['optionID'] );
    187.                 while ($row4 = db_fetch_assoc($q4))
    188.                 {
    189.                     if ($row4['variantID'] == $row3['variantID']){ //is it a default variantID
    190.                         $available_variants[0] = $row4;
    191.                     }
    192.                     else{
    193.                         $available_variants[] = $row4; //add this value to array
    194.                     }
    195.                 }
    196.                 //now write all variants
    197.                 $s = "{";
    198.                 $tmp = "";
    199.                 foreach ($available_variants as $key => $val)
    200.                 if ($val['variantID'])
    201.                 {
    202.                     $qvar = db_query("select ".LanguagesManager::ml_getLangFieldName('option_value', $defaultLanguage)." from ".PRODUCTS_OPTIONS_VALUES_VARIANTS_TABLE." where optionID=".$row2['optionID']." and variantID=".$val['variantID']);
    203.                     $rowvar = db_fetch_row($qvar);
    204.                     $s .= $tmp;
    205.                     $s .= $rowvar[0]."";
    206.                     if ($val['price_surplus']) $s .= "=".$val['price_surplus'];
    207.                     $tmp = ",";
    208.                 }else{
    209.                     $s .= ',';
    210.                 }
    211.                 $s .= "}";
    212.  
    213.                 $row3[LanguagesManager::ml_getLangFieldName('option_value', $defaultLanguage)] = $s;
    214.                 $row3['only_default'] = true;
    215.             }
    216.             /*
    217.              @features "Extra options values"
    218.              @state end
    219.              */
    220.  
    221.             $option_values[$row3['optionID']] = $row3;
    222.             //write a string into CSV file
    223.             /*
    224.              if (strstr($row3[0],"\"") || strstr($row3[0],"\n") || strstr($row3[0],$delimiter))
    225.              {
    226.                 $row3[0] = '"'.str_replace('"','""',str_replace("\r\n"," ",$row3[0])).'"';
    227.                 }
    228.                 fputs($f, $delimiter."$row3[0]");
    229.                 */
    230.         }
    231.         $option_data = array();
    232.         foreach($option_fields as $_k=>$_t){
    233.  
    234.             $option_data[$_k] = '';
    235.             list($optionID, $lang_iso2) = _parseOptionKey($_k);
    236.             if(isset($option_values[$optionID]['only_default'])){
    237.  
    238.                 if($lang_iso2 == $defaultLanguage->iso2){
    239.                        
    240.                     $option_data[$_k] = $option_values[$optionID][LanguagesManager::ml_getLangFieldName('option_value', $defaultLanguage)];
    241.                 }
    242.                 continue;
    243.             }else{
    244.                    
    245.                 $option_data[$_k] = $option_values[$optionID]['option_value_'.$lang_iso2];
    246.             }
    247.                
    248.             if (strstr($option_data[$_k],"\"") || strstr($option_data[$_k],"\n") || strstr($option_data[$_k],$delimiter)){
    249.  
    250.                 $option_data[$_k] = '"'.str_replace('"','""',str_replace("\r\n"," ",$option_data[$_k])).'"';
    251.             }
    252.         }
    253.  
    254.         if(count($option_data)){
    255.             fputs($f, $delimiter.implode($delimiter, $option_data));
    256.         }
    257.         fputs($f,"\n");
    258.     }
    259. }
    260.  
    261. function _exportSubCategoriesAndProducts($parent, $level, &$f, $delimiter=";") //exports products and subcategories of $parent to a CSV file $f
    262. //a recurrent function
    263. {
    264.     $cnt = 0;
    265.     $q = db_query("select categoryID,".LanguagesManager::sql_constractSortField(CATEGORIES_TABLE, 'name')." from ".CATEGORIES_TABLE." where parent=$parent order by sort_order, ".LanguagesManager::sql_getSortField(CATEGORIES_TABLE, 'name'));
    266.  
    267.     //fetch all subcategories
    268.     while ($row = db_fetch_row($q))
    269.     {
    270.         _exportCategoryLine($row[0], $level, $f, $delimiter);
    271.         _exportProducts($row[0], $f, $delimiter);
    272.            
    273.         //process all subcategories
    274.         _exportSubCategoriesAndProducts($row[0], $level+1, $f, $delimiter);
    275.     }
    276.  
    277. } //_exportSubCategoriesAndProducts
    278.  
    279. function escapeCSVField($string, $delimiter){
    280.  
    281.     if (strstr($string,'"') || strstr($string,"\n") || strstr($string,$delimiter)){
    282.         $string = '"'.str_replace('"','""',str_replace(array("\r\n", "\n", "\r")," ",$string)).'"';
    283.     }
    284.  
    285.     return $string;
    286. }
    287.  
    288. //products and categories catalog import from MS Excel .CSV files
    289.  
    290. if (isset($_POST["excel_export"])) //export products
    291. {
    292.     @set_time_limit(0);
    293.  
    294.     if ($_POST["delimiter"]==";" || $_POST["delimiter"]=="," || $_POST["delimiter"]=="\t"|| $_POST["delimiter"]=='\t'){
    295.         $delimiter = $_POST["delimiter"];
    296.         if($delimiter == '\t'){
    297.             $delimiter = "\t";
    298.         }
    299.     }else{
    300.         $delimiter = ";";
    301.     }
    302.     $export_file_name = (CONF_SHOP_NAME?preg_replace('/[^a-z_0-9]/ui', '_', 'catalog_'.strtolower(translit(CONF_SHOP_NAME))):'catalog');
    303.     $export_file_name_extension = '_'.strtolower($_POST['charset']).'.csv';
    304.    
    305.     $export_file_name = substr($export_file_name,0,(128-strlen($export_file_name_extension)));
    306.     $export_file_name .= $export_file_name_extension;
    307.    
    308.  
    309.     $f = fopen(DIR_TEMP."/{$export_file_name}","w");
    310.     $product_fields = _getProductFields();
    311.  
    312.     //write a header line
    313.     fputs($f, implode($delimiter, xCall('escapeCSVField', $product_fields, $delimiter)));
    314.  
    315.     //calculate the number of 'Picture' columns
    316.     $max = 1;
    317.     /**
    318.      * @features "Multiple image-sets for product"
    319.      * @state begin
    320.      */
    321.     $q = db_query("SELECT COUNT(productID) FROM ".PRODUCT_PICTURES." GROUP BY productID");
    322.     $max = 1;
    323.     $result = array();
    324.     while ($row = db_fetch_row($q)){
    325.  
    326.         if ($max < $row[0]) $max = $row[0];
    327.     }
    328.     /**
    329.      * @features "Multiple image-sets for product"
    330.      * @state end
    331.    
    332.     Unset by Invision
    333.    
    334.     for ($i=1;$i<=$max;$i++)
    335.     {
    336.         fputs($f, $delimiter.xCall('escapeCSVField', translate("prdset_product_picture"), $delimiter));
    337.     }
    338.     $picture_columns_count = $max;
    339.     $option_fields = _getOptionFields();
    340.     $extra_columns_count = count($option_fields);
    341.     if($extra_columns_count){
    342.         fputs($f, $delimiter.implode($delimiter, xCall('escapeCSVField', $option_fields, $delimiter)));
    343.     }
    344.     fputs($f,"\n");
    345.  */
    346.     //export selected products and categories
    347.     //root
    348.     if (isset($_POST["categ_1"]))
    349.     {
    350.         _exportProducts(1, $f, $delimiter);
    351.     }
    352.     //other categories
    353.     $dbq = "
    354.         SELECT categoryID, ".LanguagesManager::sql_constractSortField(CATEGORIES_TABLE, 'name')."
    355.         FROM ".CATEGORIES_TABLE." WHERE parent=1 ORDER BY sort_order, ".LanguagesManager::sql_getSortField(CATEGORIES_TABLE, 'name');
    356.     $q = db_query($dbq);
    357.     $result = array();
    358.     while ($row = db_fetch_row($q))
    359.     if (isset($_POST["categ_$row[0]"]))
    360.     {
    361.         _exportCategoryLine($row[0], 0, $f, $delimiter);
    362.         _exportProducts($row[0], $f, $delimiter);
    363.         _exportSubCategoriesAndProducts($row[0], 1, $f, $delimiter);
    364.     }
    365.  
    366.     fclose($f);
    367.  
    368.     if($_POST['charset'] && $_POST['charset'] != DEFAULT_CHARSET){
    369.         File::convert(DIR_TEMP."/{$export_file_name}",DEFAULT_CHARSET,$_POST['charset']);
    370.         //iconv_file(DEFAULT_CHARSET, $_POST['charset'], DIR_TEMP."/{$export_file_name}");
    371.     }
    372.     xPopData('EXPORT_PRODUCTS2CSV');
    373.     xSaveData('EXPORT_PRODUCTS2CSV',array('file'=>base64_encode($export_file_name)),3600);
    374.     RedirectSQ('&export_completed=yes');
    375. }
    376.  
    377. if (isset($_GET["export_completed"])) //show successful save confirmation message
    378. {
    379.     $file = xPopData('EXPORT_PRODUCTS2CSV');
    380.     //$file = isset($_GET['file'])?base64_decode($_GET['file']):'';
    381.     $file = isset($file['file'])?base64_decode($file['file']):'';
    382.     set_query('export_completed=','',true);
    383.     if ($file && file_exists(DIR_TEMP."/{$file}"))
    384.     {
    385.         $getFileParam = Crypt::FileParamCrypt( "GetCSVCatalog=".base64_encode($file), null );
    386.         $smarty->assign( "getFileParam", $getFileParam );
    387.  
    388.         $smarty->assign("excel_export_successful", 1);
    389.         $smarty->assign("excel_filesize", (string) round( filesize(DIR_TEMP."/{$file}") / 1024 ) );
    390.     }
    391. }else{ //prepare categories list
    392.  
    393.     $dbq = "
    394.         SELECT categoryID, ".LanguagesManager::sql_constractSortField(CATEGORIES_TABLE, 'name')."
    395.         FROM ".CATEGORIES_TABLE." WHERE parent=1 ORDER BY sort_order, ".LanguagesManager::sql_getSortField(CATEGORIES_TABLE, 'name');
    396.     $q = db_query($dbq);
    397.     $result = array();
    398.     while ($row = db_fetch_row($q)) $result[] = $row;
    399.     $smarty->assign("categories",$result);
    400. }
    401.  
    402. global $file_encoding_charsets;
    403. $smarty->assign('charsets', $file_encoding_charsets);
    404. $smarty->assign('default_charset', translate('prdine_default_charset'));
    405. $smarty->assign('admin_sub_dpt', "catalog_excel_export.tpl.html");
    406. ?>
    Вся проблема в разделителе... К примеру у товара имя Samsung Star то разбивается на 2 столбца. Первый это Samsung второй Star. Название стобцов путаются итд. Пытаюсь разобраться но с CSV вообще дела не имел. Если не трудно подскажите мб вы знаете как правильно вывести без разделитиля -_-
     
  2. Invision

    Invision Активный пользователь

    С нами с:
    26 фев 2009
    Сообщения:
    1.437
    Симпатии:
    1
    Адрес:
    Томск
    вообщем проще с нуля написать)
     
  3. titch

    titch Активный пользователь

    С нами с:
    18 дек 2010
    Сообщения:
    847
    Симпатии:
    0