How to save node content to a file and attach it
This is how you can save node content to a file and attach it. In this case I have a translated version of the title and the body as I save to $data variable.
I have a certain filename pattern, and I first look if the node has a file saved already, know if I should update records or insert new in files and upload tables.
You have to set chmod 777 on the folder to be able to save files.
<?php
/**
* Takes node title and body (translated) and saves it to a file
* and update Drupal records for files and upload to connect it to node
*
* @param unknown_type $node
* @return unknown
*/
function _save_content_to_file($node) {
$data .= "<H1>".$node->field_t_title[0]['value']."</H1>";
$data .= $node->field_t_body[0]['value'];
$dest = file_directory_path();
$file_drupal_path = $dest."/mymodule/html/".$node->nid."_content.txt";
$mime = 'text/plain';
$file_drupal_path = file_save_data($data, $file_drupal_path, FILE_EXISTS_REPLACE);
if (count($node->files) > 0) {
foreach ($node as $fid => $nodefile) {
if ($nodefile['filepath'] == $file_drupal_path) {
$file_exist_on_node = 'fid';
}
}
}
$file = new stdClass();
$file->filename = basename($file_drupal_path);
$file->description = $file->filename;
$file->filepath = $file_drupal_path;
$file->filemime = $mime;
$file->list = 1;
$file->weight = 0;
$file->filesize = filesize($file_drupal_path);
$file->uid = $node->uid;
$file->nid = $node->nid;
$file->vid = $node->vid;
$file->status = FILE_STATUS_PERMANENT;
$file->timestamp = time();
drupal_write_record('files', $file, $file_exist_on_node);
drupal_write_record('upload', $file, $file_exist_on_node);
return $file;
}
//In my code I call for the function like this:
$file = _save_content_to_file($node);
if ($file->fid > 0) {
$node->files[$file->fid] = $file;
}
node_save($node);
?>
Knowledge keywords: