Skip to content

Instantly share code, notes, and snippets.

@sidor1989
Created June 6, 2019 10:37
Show Gist options
  • Save sidor1989/9e052e89220445533d61a5049d2e05b2 to your computer and use it in GitHub Desktop.
Save sidor1989/9e052e89220445533d61a5049d2e05b2 to your computer and use it in GitHub Desktop.
<?php
## Читает CSV файл и возвращает данные в виде массива.
## @param string $file_path Путь до csv файла.
## string $col_delimiter Разделитель колонки (по умолчанию автоопределине)
## string $row_delimiter Разделитель строки (по умолчанию автоопределине)
## ver 6
ini_set('display_errors', 1);
ini_set('error_reporting', -1);
//конфиги
$file = 'price.csv';
function getPriceFromString($string) {
//меняем запятую на точку
$string = preg_replace('/,/', '.', $string);
//берем только цифры и точку
$string = preg_replace('/[^.\d]/', '', $string);
return $string;
}
function getCurrency($string) {
preg_match('/USD|EUR|руб/', $string, $matches);
return $matches[0];
}
function kama_parse_csv_file( $file_path, $file_encodings = ['cp1251','UTF-8'], $col_delimiter = '', $row_delimiter = "" ){
if( ! file_exists($file_path) )
return false;
$cont = trim( file_get_contents( $file_path ) );
$encoded_cont = mb_convert_encoding( $cont, 'UTF-8', mb_detect_encoding($cont, $file_encodings) );
unset( $cont );
// определим разделитель
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 );
// авто-определим разделитель из двух возможных: ';' или ','.
// для расчета берем не больше 30 строк
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 $key => $line ){
$data[] = str_getcsv( $line, $col_delimiter ); // linedata
unset( $lines[$key] );
}
return $data;
}
//делаем массив из csv
$data = kama_parse_csv_file($file);
echo'<pre>';
foreach($data as $item){
if ( empty($item[2])) continue;
//берем артикул из массива
$article = strtolower($item[2]);
//берем цену из массива
$price = getPriceFromString($item[3]);
//берем валюту
$currency = getCurrency($item[3]);
// запрос на обновление цен
$sql = "UPDATE wp_ms2_products SET base_price = {$price} WHERE article = {$article}";
$count = $modx->exec($sql);
// Получим количество обновленных записей
print("Обновлено - $count - записей.<br>");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment