Importing data from a CSV file


For that, you should create a PHP file (For example, in the DOCUMENT_ROOT of Drupal) and include the source code that indicates continuation. In order to use the Drupal API in this PHP file, said file should be executed with Drush:

drush scr <ruta/nombre_fichero.php>

  // Script configuration.
  $script = array(
    'file_name' => 'Example.csv',
    'file_directory' => 'csv',


   * Import data from a CSV file.
   * @param $script
   *  Path to the CSV file.
  function importData($script) {
    $file = fopen("public://{$script['file_directory']}/{$script['file_name']}", 'r');
    // Read the document header,
    // this row shouldn't be processed.
    $csv_file = fgetcsv($file, '', ",");

    while (!feof($file)) {
      // Get each row from a CSV file,
      // generating a PHP array.
      $csv_file = fgetcsv($file, '', ",");

      // Your query here...


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.