function createNode($data = array(), $filepath = NULL) {
//private function,not necessary to read/copy
//the
$node = new stdClass;
$node->type = "story";
$node->nid = 0;
$node->uid = 1;
$node->status = 1;
$node->promote = 1;
$node->changed = $node->created = time();
$node->sticky = 0;
$node->format=2;
$node->title = 'demo node';
$node->body = 'demo content';
//$node->taxonomy=array(1,2);
foreach($data as $key => $val) {
$node->$key = $val;
}
if($filepath) {
$file=_ufileobj($filepath);
$filearray=_cck_filepre($file);
$node->field_image[0]= $filearray; // 文件字段,手工改动
}
node_save($node);
$nid=$node->nid;
$node=NULL;
return $nid;
}
function _ufileobj($filepath) {
// Create a new file record --object
//print_r(ufileobj( file_directory_path()."/test/test1.flv" ));
$file = new stdClass();
//$file->fid=NULL;//when upload success , will return
$file->list = 1;
//data igore
$file->uid = $uid;
$file->filename = basename($filepath);
$file->filepath = $filepath;
$file->filemime = file_get_mimetype(basename($filepath));
$file->filesize = filesize($filepath);
// You can change this to the UID you want
$file->status = 1;
$file->timestamp = time();
$file->new = true;//addition field , seems useless
drupal_write_record('files', $file);
// file_set_status($file,1);
//$node->files[$file_obj->fid] = $file_obj;
return $file;
}
function _cck_filepre($file) {
//return file array which suits drupal cck file field
//$file is the result ofufileobj($filepath);
$filearray=array();
$filearray[fid]=$file->fid;
$filearray["list"]=1;
$filearray[data]=array("description"=>"","alt"=>"","title"=>"");
$filearray[uid]=1;
$filearray[filename]=$file->filename;
$filearray[filepath]=$file->filepath;
$filearray[filemime]=$file->filemime;
$filearray[filesize]=$file->filesize;
$filearray[status]=1;
$filearray[timestamp]=$file->timestamp;
return $filearray;
}
转载于:https://www.cnblogs.com/catcat811/archive/2011/02/11/1951642.html