Skip to content

Instantly share code, notes, and snippets.

@eto4detak
Created February 2, 2018 13:06
Show Gist options
  • Save eto4detak/3c821949d2f7d4f507a39f9408d57c0e to your computer and use it in GitHub Desktop.
Save eto4detak/3c821949d2f7d4f507a39f9408d57c0e to your computer and use it in GitHub Desktop.
drupal php excel sql addProduct
<?php
/**
* Submit function for calculator_page_form.
*/
function import_excel_page_form_submit($form, &$form_state) {
$uri = $form_state['values']['file']->uri;
$data = import_excel_parse_csv_file($uri);
$data = import_excel_filterData($data);
$db_product = import_excel_getProductDB($data);
$result = import_excel_changeNodes($data, $db_product);
if($result[0] !== 0) drupal_set_message(t("Добавлено продуктов: %number", array('%number' => $result[0])));
if($result[1] !== 0) drupal_set_message(t("Обновлено продуктов: %number", array('%number' => $result[1])) );
}
function import_excel_getProductDB($data){
$models = array_column($data , 'sku');
$query = 'SELECT model, nid FROM {uc_products} WHERE';
foreach ($models as $k => $value) {
if($k === 0) $query .= ' model = ' . "'$value'";
else $query .=' OR' . ' model = ' . "'$value'";
}
$db_products = db_query($query)->fetchAll();
$result = [];
foreach ($db_products as $product) {
$result[] = array('model' => $product->model, 'nid' => $product->nid);
}
return $result;
}
function import_excel_filterData($data){
unset($data[0]);//удалить первую строку
$new_data = [];//удалить копии
$select_sku =[];
foreach($data as $row) {
if(!in_array($row[1], $select_sku)) {
$select_sku[] = $row[1];
$new_data[] = $row;
}
}
$data = $new_data;
$data_excel = [];//в ассоциативны массив
foreach ($data as $row) {
if(empty($row[0]) || empty($row[1])) continue;
$data_excel[] =
array('title' => $row[0],
'sku' => $row[1],
'list_price'=> (int)$row[2],
'cost' => (int)$row[3],
'price' => (int)$row[4],
'weight' => (int)$row[5],
'length' => (int)$row[6],
'width' => (int)$row[7],
'height' => (int)$row[8],
'category' => $row[9],
'body' => $row[10]);
}
return $data_excel;
}
function import_excel_changeNodes($data, $db_product){
$count_add = 0;
$count_update = 0;
foreach ($data as $product_excel) {
if(in_array($product_excel['sku'], array_column($db_product , 'model'))) {
import_excel_update_node($product_excel, $db_product);
$count_update++;
}else{
import_excel_make_node($product_excel);
$count_add++;
}
}
return [$count_add , $count_update];
}
function import_excel_make_node($data){
$body_text = $data['body'];//add node
$node = new stdClass();
$node->type = 'product';
node_object_prepare($node);
$node->language = LANGUAGE_NONE;//add data
$node->status = 1;
$node->shippable = 1;
$node->default_qty = 1;
$node->title = $data['title'];
$node->model = $data['sku'];
$node->list_price = $data['list_price'];
$node->cost = $data['cost'];
$node->sell_price = $data['price'];
$node->weight = $data['weight'];
$node->length = $data['length'];
$node->width = $data['width'];
$node->height = $data['height'];
$node->body[$node->language][0]['value'] = $body_text;
$node->body[$node->language][0]['summary'] = text_summary($body_text);
$node->body[$node->language][0]['format'] = 'filtered_html';
$tax_id = import_excel_get_id_tax($data['category']);//add taxonomy
if(!empty($tax_id)) $node->taxonomy_catalog[$node->language][0]['tid'] =$tax_id;
else unset($node->taxonomy_catalog[$node->language][0]);
if ( $node = node_submit($node)){
node_save($node);
}
return $node;
}
function import_excel_get_id_tax($category){
$term = taxonomy_get_term_by_name($category);
if(!empty($term))
return $term[key($term)]->tid;
}
function import_excel_update_node($data, $products_db){
$key = array_search($data['sku'], array_column($products_db , 'model'));//update taxonomy
$node = node_load($products_db[$key]['nid']);
$tax_id = import_excel_get_id_tax($data['category']);
if(!empty($tax_id)) $node->taxonomy_catalog[$node->language][0]['tid'] =$tax_id;
else unset($node->taxonomy_catalog[$node->language][0]);
node_save($node);
$node_wrapper = entity_metadata_wrapper('node', $node);//update data
$node_wrapper->title->set($data['title']);
$node_wrapper->list_price->set($data['list_price']);
$node_wrapper->cost->set($data['cost']);
$node_wrapper->sell_price->set($data['price']);
$node_wrapper->weight->set($data['weight']);
$node_wrapper->length->set($data['length']);
$node_wrapper->width->set($data['width']);
$node_wrapper->height->set($data['height']);
$node_wrapper->body->set(array('value' => $data['body']));
$node_wrapper->save();
return $node;
}
function import_excel_parse_csv_file( $file_path, $file_encodings = ['cp1251','UTF-8'], $col_delimiter = '', $row_delimiter = "" ){
if( ! file_exists($file_path) )
return false;
$cont = iconv('cp1251','utf-8', trim( file_get_contents( $file_path ) ));
$encoded_cont = mb_convert_encoding( $cont, 'UTF-8', mb_detect_encoding($cont, $file_encodings) );
if( ! $row_delimiter ){
$row_delimiter = "\r\n";
if( false === strpos($encoded_cont, "\r\n") )
$row_delimiter = "\n";
}
$lines = explode( $row_delimiter, trim($encoded_cont) );
$lines = array_filter( $lines );
$lines = array_map( 'trim', $lines );
if( ! $col_delimiter ){
$lines10 = array_slice( $lines, 0, 30 );
foreach( $lines10 as $line ){
if( ! strpos( $line, ',') ) $col_delimiter = ';';
if( ! strpos( $line, ';') ) $col_delimiter = ',';
if( $col_delimiter ) break;
}
if( ! $col_delimiter ){
$delim_counts = array( ';'=>array(), ','=>array() );
foreach( $lines10 as $line ){
$delim_counts[','][] = substr_count( $line, ',' );
$delim_counts[';'][] = substr_count( $line, ';' );
}
$delim_counts = array_map( 'array_filter', $delim_counts );
$delim_counts = array_map( 'array_count_values', $delim_counts );
$delim_counts = array_map( 'max', $delim_counts );
if( $delim_counts[';'] === $delim_counts[','] )
return array('Не удалось определить разделитель колонок.');
$col_delimiter = array_search( max($delim_counts), $delim_counts );
}
}
$data = [];
foreach( $lines as $line ){
$data[] = str_getcsv( $line, $col_delimiter ); // linedata
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment