Skip to content

Instantly share code, notes, and snippets.

@andronex
Created December 1, 2022 02:29
Show Gist options
  • Save andronex/dffd6bb7b82e3fe3541a384d9dedf098 to your computer and use it in GitHub Desktop.
Save andronex/dffd6bb7b82e3fe3541a384d9dedf098 to your computer and use it in GitHub Desktop.
Парсер цветов RAL с сайта https://ral.ru/classic_colours для MODX из Console с сохранением в свою кастомную таблицу
<?php
$modx->addPackage('colorsProducts', MODX_CORE_PATH . 'components/colorsProducts/model/');
$url = 'https://ral.ru/classic_colours';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_ENCODING => "",
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17",
CURLOPT_AUTOREFERER => true,
CURLOPT_CONNECTTIMEOUT => 120,
CURLOPT_TIMEOUT => 120,
CURLOPT_MAXREDIRS => 10,
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
curl_close( $ch );
if(!function_exists('downloadImg')){
function downloadImg($image, $urlImages){
global $modx;
$path = MODX_BASE_PATH . 'assets/coloring/ral/';
$image = str_replace(['_',' ','—','.bmp','.BMP'], ['-','-','-','.jpg','.jpg'], $image);
if (!file_exists($path.$image) || filesize($path.$image) < 100) {
$ch = curl_init($urlImages);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(!file_put_contents($path.$image, curl_exec($ch))){
$modx->log(modX::LOG_LEVEL_ERROR, "Неудача при скачивании картинки цвета {$urlImages}");
return '';
}
curl_close($ch);
}
return str_replace(MODX_BASE_PATH,'',$path).$image;
}
}
$doc = new DOMDocument();
$doc->loadHTML($content);
$xpath = new DOMXpath($doc);
$elements = $xpath->query("//ul[@class='cat']/li/a/img");
foreach($elements as $img){
$title_rus = trim($img->attributes->getNamedItem('title')->value);
$img_color = 'https://ral.ru/' . $img->attributes->getNamedItem('src')->value;
$ral_name = trim($img->parentNode->nodeValue);
$img_color_name = end(explode('/', $img_color));
if(!$modx->getObject('ColoringProducts', ['name' => $ral_name])){
$newColor = $modx->newObject('ColoringProducts');
$newColor->set('name', $ral_name);
$newColor->set('colorname', $title_rus);
$newColor->set('type', 'ral');
$newColor->set('img', downloadImg($img_color_name, $img_color));
$newColor->set('price', 500);
$newColor->set('price_kraski', 900);
$newColor->set('price_gruntovki', 650);
$newColor->save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment