从CSV文件读取节点并使用批处理保存 - Drupal 7

时间:2017-09-23 16:37:15

标签: php csv drupal drupal-7 batch-processing

当我尝试使用批处理保存节点时,我收到此错误:

  

PDOException:在drupal_write_record()中(C:\ wamp64 \ www \ drupal7 \ includes \ common.inc的第7383行)。

这是我的完整代码:

function custom_node_import_form_submit($form, &$form_state) {
  $csvFile = file_load($form_state['values']['csv_file']);
  $csvFilepath = drupal_realpath($csvFile->uri);
  $file = fopen($csvFilepath, "r");

  $batch = array(
    'operations' => array(),
    'finished' => 'node_import_finished',
    'title' => t('Node import'),
    'init_message' => t('Importing is starting...'),
    'progress_message' => t('Imported @current out of @total.'),
    'error_message' => t('Node importer has encountered an error.')
  );

  fgetcsv($file, 0, ",");
  while($line = fgetcsv($file)) {
    $batch['operations'][] = array('node_import_progress', array(array_map('base64_encode', $line)));
  }

  batch_set($batch);
  batch_process('admin/node/custom-node-import');
  fclose($file);
}

function node_import_progress($line, &$context) {
  $line = array_map('base64_decode', $line);
  saveNode($line);
  $context['message'] = t('Importing %title', array('%title' => $line[0]));
}

function node_import_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Node importing is complete!'));
  }
  else {
    $error_operation = reset($operations);
    $message = t('An error occurred while processing %error_operation with arguments: @arguments', array(
      '%error_operation' => $error_operation[0],
      '@arguments' => print_r($error_operation[1], TRUE)
    ));
    drupal_set_message($message, 'error');
  }
}
function saveNode($param = []) {
  global $user;

  $node = new stdClass();
  $node->title = $param[0];
  $node->type = "article";
  node_object_prepare($node);
  $node->language = LANGUAGE_NONE;
  $node->uid = $user->uid; 
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;      
  $node->body[$node->language][]['value'] = $param[3];

  $node = node_submit($node);
  node_save($node);
}

我已调试并发现给出此错误的行是节点被保存的最后一行。即 node_save($ node);

2 个答案:

答案 0 :(得分:1)

问题在于CSV文件中的非英文字符,如ö,ä等

所以解决方案是使用utf8_encode()作为值:

$node->title = utf8_encode($param[0]);
$node->body[$node->language][]['value'] = utf8_encode($param[3]);

希望它对某人有帮助。

答案 1 :(得分:0)

您还可以为所有值添加转换,如下所示:

array_walk($param, function(&$value){
  $value = mb_convert_encoding($value, 'UTF-8', mb_detect_encoding($value));
});