Tel: 91-98574-11333 | Mail: inderweb.com@gmail.com


Creating Drupal Script for inserting / importing data from external sources

Migrating to Drupal can seem intimidating if you already maintain a database-driven website.When interacting with Drupal, it's a good idea to do things the Drupal way. Fortunately, Drupal core allows you to bootstrap Drupal and use all of its API functionality outside of a normal Drupal instance. For yours truly, learning about this has been a godsend because it provides a fast, simple way to migrate data

When writing an import script, you will need to bootstrap Drupal to use the API functions. Using drupal_bootstrap($phase), you can load Drupal up to a certain loading phase by designating a $phase argument. The value of $phase allows you to specifically load the site configuration, database layer, modules and other requisite functionality. For our purposes, we will use drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL) to make sure that we have access to the whole API.

Note: Make sure that you create this script in the root of your Drupal installation.

Lets create a php file database-import.php and place it in drupal root installation.Copy / modify code below and place it in database-import.php file.

<?php
// Bootstrap Drupal loading
require 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

For a simple example, we will create a basic node object and save it in our Drupal database using node_save().

<?php
// Construct the new node object.
//Add loo around it for multiple nodes / pages
$node = new stdClass();
//require 'modules/node/node.pages.inc'; // Can add node file if you getting any error
// Your script will probably pull this information from a database.
$node->title = "My Node page title";
$node->body = "The Page or node body of my imported node.\n\nAdditional Information. Can be full loaded HTML from outsource";
$node->type = 'page'
//node_object_prepare($node);  Optionally can call this for auto preparing node
// Your specified content type must be in drupal I am taking default one which is already in drupal
$node->created = time();
$node->changed = $node->created;
$node->status = 1; // Published by default
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;       // Filtered HTML
$node->uid = 1;          // UID of content owner
$node->language = 'en';
// If known, the taxonomy TID values can be added as an array.
//$node->taxonomy = array(2,3,1);// If you have categories then you need to add vocublaries first and then add vid here by comma seperated string.

node_save($node);// FInally call drupal function for saving node in database.
?>

Thats it ...!! so simple drupal migration :-) . Just need to add in cron if there are thousands of nodes / pages. Script may need modifications and corrections. This is just a basic idea.

Tags for Creating Drupal Script for inserting / importing data from external sources