Drupal: импорт контента из XML на примере партнерки Gameboss

plyaski-s-bubnomЕсли порыться в сети можно найти туеву хучу недописанных “мануалов” типа “миграция из Wordpress в Drupal”, которые по сути не раскрывают главного – алгоритма автоматического добавления материалов в Drupal. Описывать процесс переноса материалов из вордпресса в друпал я не стану, прочитав эту статью до конца вы сможете сами это сделать. Я же покажу более сложный и интересный пример.

Итак, задача: сделать автонаполняемый сайт на лучшей в мире ;) CMS Drupal с контентом от партнерской программы Gameboss.

Как известно основа основ в Drupal – это CCK. Для реализации поставленной задачи, с помощью CCK был создан тип материала – “game”, который содержит поля:

  • field_game_fulldescr – полное описание игры
  • field_game_shortdescr – краткое описание игры
  • field_game_nameurl – название игры, которое используется при формировании ссылки
  • field_game_download_link – ссылка на скачивание игры
  • field_game_added – дата добавления игры
  • field_game_type – раздел (жанр) игры
  • field_game_size – “вес” игры в МБ
  • field_game_medium_pic – картинка игры (а-ля лого), испольщуется в блоках и в описании игры
  • field_game_small_pic – миниатюра изображения игры
  • field_game_screenshot – скриншот из игры
  • field_game_screenshot_thumbnail – превью скриншота из игры

Алгоритм, в принципе, прост. Парсим xml (строки 40-44), заполняем соответствующие поля (строки 47 – 83), сохраняем новый материал (строка 89). С изображениями (75-76) возни немного больше – все описано в функции load_imagefield.

<?php
require 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

//$sampleNode = node_load('3');
//echo "<PRE>" . print_r($sampleNode, TRUE) . "</pre>";
//die();

function load_imagefield($image,&$imagefilename){
$img					= str_replace(" ","%20",$image);
$file_temp				= file_get_contents("$img");
$importdir				= file_directory_path();

if (!$imagefilename){
$imagefilename			= md5($img . time()) . '.jpg';
} else {
$imagefilename			= $imagefilename .'.thumb.jpg';
}
$file_temp				= file_save_data($file_temp, $importdir .'/'. $imagefilename, FILE_EXISTS_RENAME);

$imagefile 				= image_get_info($importdir. '/' . $imagefilename);
$imagefile['list'] 		= true;
//			$imagefile['data']['description'] = 'description text';
//			$imagefile['data']['title'] = 'title';
//			$imagefile['data']['alt'] = $gamename;

$imagefile['filename']	= $imagefilename;
$imagefile['filepath']	= $importdir . '/' . $imagefilename;
$imagefile['filemime']	= $imagefile['mime_type'];
$imagefile['filesize']	= $imagefile['file_size'];
$imagefile['uid']		= 1;
$imagefile['status']	= FILE_STATUS_PERMANENT;
$imagefile['timestamp']	= time();
$file 					= $imagefile;
drupal_write_record('files', $file);
$imagefile['fid'] 		= $file['fid'];
return $imagefile;
}

$url = "http://gameboss.ru/x2.php?partner=***ID_партнера***&short=1&full=1&image=1&limit=1000";
$page=file_get_contents($url);

$xml = simplexml_load_string($page);
$items = $xml->xpath('/response/result/ITEM');
$gamecnt=1;
foreach ($items as $item) {
$node = new StdClass();
$node->type = 'game';
$node->uid = 1;
$node->created = strtotime($item->ADDED);
$node->changed = strtotime($item->ADDED);
$node->status = 1;
$node->comment = 2;
$node->promote = 1;
$node->moderate = 0;
$node->sticky = 0;

$node->title								=	$item->NAME;
$node->field_game_id[0]['value']			=	$item->ID;
$node->field_game_name[0]['value']			=	$item->NAME;
print $gamecnt."\t".$item->NAME."<br>";
$node->field_game_fulldescr[0]['value']		=	$item->FULLDESCR;
$node->field_game_shortdescr[0]['value']	=	$item->SHORTDESCR;
$node->field_game_name_url[0]['value']		=	$item->NAME_URL;
$node->field_game_download_link[0]['url']	=	$item->DOWNLOAD_LINK;
$node->field_game_added[0]['value']			=	$item->ADDED;
$node->field_game_type[0]['value']			=	$item->TYPE;
$node->field_game_size[0]['value']			=	$item->SIZE;
$tmp="";$node->field_game_medium_pic[]		=	load_imagefield($item->MEDIUM_PIC,$tmp);
$tmp="";$node->field_game_small_pic[]		=	load_imagefield($item->SMALL_PIC,$tmp);

$sshots = $item->xpath('SCREENSHOT');
foreach ($sshots as $img) {
$imagename="";
$node->field_game_screenshot[]	=	load_imagefield($img->IMAGE,$imagename);
$node->field_game_screenshot_thumbnail[]	=	load_imagefield($img->THUMBNAIL,$imagename);
}
for ($i=0;$i<8;$i++) if ($node->field_game_type[0]['value'] & (1<<$i)) {
$node->taxonomy[1][]=$i+1;
}
print "<br>";

//$node = node_submit($node);
node_save($node);
$gamecnt++;
flush();
}
?>
If you enjoyed this post, make sure you subscribe to my RSS feed!

Метки : ,
Почитайте еще и эти статьи:
Комментариев нет. Станьте первым комментатором!
Оставить комментарий!

Имя

E-mail

URL

Я не робот, я не хрумер, я не спамер.

Предыдущая запись
«
Следующая запись
»