Hi

I am creating nodes programmatically when my module is enabled. This works fine.

Now I would like to read the content of a file embedded in the module package and use this content to create my node

So far I have managed to read it using the absolute path in the file system:

  $filename = "/var/www/html/sites/all/modules/custom/my_module/node_content.html";
  $handle = fopen($filename, "r");
  $body_content = fread($handle, filesize($filename));
  fclose($handle);

...but obviously I need to specify a relative path.

This for instance does not work to open the file:

$filename = "./node_content.html";

which is weird because the file node_content.html is in the same folder as my_module.install.

Do you have any recommendation to solve this problem? Is there a better way to proceed?

Regards.
Pascal

Comments

jeditdog’s picture

Use DRUPAL_ROOT. So instead:

 $filename = DRUPAL_ROOT . "/sites/all/modules/custom/my_module/node_content.html";
pmaugeri’s picture

It works beautifully! Thank you so much for the tip ;-)

apaderno’s picture

Instead of using an absolute path for the file, the code should use drupal_get_path() to get the directory where the module is installed.

$filename = drupal_get_path('module', 'my_module') . '/node_content.html';
$handle = fopen($filename, "r");
$body_content = fread($handle, filesize($filename));
fclose($handle);