Blog Archive

Thursday, 17 October 2013

Drupal 7 - Creating nodes with multiple images which already existing in public:// folder.

Her we creating nodes containing multiple images for each node. All these images already uploaded to the server under public://(sites/default/files/). And get all the information about the pictures and  nodes in .csv file under "sites/all/".

Formatting the CSV.
1) All columns except for date should end with a semicolon
2) If we have multiple images in the same row, it should be separated with a '+'.



<?php
$image_node_csv = array();
if (($handle = fopen("sites/all/check_name.csv", "r")) !== FALSE) {
  $row = 1;
  while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
    $num = count($data);
    $image_node_csv[$row] = $data;
    $row++;
  }
  fclose($handle);
}
$count_node_to_creat = count($image_node_csv);
for ($i = 2; $i <= $count_node_to_creat ; $i++){
  $node = new StdClass();
  $node->type = 'test';
  $node->language = LANGUAGE_NONE;
  $node->title = preg_replace('/\s+/','',$image_node_csv[$i][0]);
  $node->body['und']['0']['value'] = preg_replace('/\s+/','',$image_node_csv[$i][1]);
  $image = explode('+',$image_node_csv[$i][2]);
  $count_image = count($image);
  for($j = 0; $j < $count_image; $j++){
    $image_path = "sites/default/files/".preg_replace('/\s+/','',$image[$j]);
    $filepath = drupal_realpath($image_path);
    $file = (object) array(
      'uid' => 1,
      'uri' => $filepath,
      'filemime' => file_get_mimetype($filepath),
      'status' => 1,
    );
    $file = file_copy($file, 'public://');
    $node->field_test_images1[LANGUAGE_NONE][$j] = (array)$file;
 }
  node_save($node);
}
?>

No comments:

Post a Comment