<?php

function newtest_menu() {
$items = array();
$items['import/csv'] = array(
'title' => 'Import CSV',
'page callback' => 'drupal_get_form',
'page arguments' => array('newtest_csv_import_form'),
'access arguments' => array('access content'),
'type' => MENU_LOCAL_TASK,
);
$items['export/csv'] = array(
'title' => 'Export CSV',
'page callback' => 'drupal_get_form',
'page arguments' => array('newtest_csv_export_form'),
'access arguments' => array('access content'),
'type' => MENU_LOCAL_TASK,
);
return $items;
}

function newtest_csv_import_form($form, &$form_state){
$form['name'] = array(
'#type' => 'select',
'#title' => t('Select Node'),
'#options' => node_type_get_names(),
);
$form['choose_file'] = array(
'#type' => 'managed_file',
'#title' => t('Import CSV file'),
'#description' => t('csv, xml, txt format only'),
'#required' => TRUE,
'#upload_location' => 'public://MyImportCSV',
'#upload_validators' => array('file_validate_extensions' => array('csv xml txt')),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Import CSV file',
);
return $form;
}

function newtest_form_submit($form, &$form_state) {
$file = file_load($form_state['values']['choose_file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
drupal_set_message(t('The csv file is uploaded'));
}

function newtest_csv_export_form($form, &$form_state) {
$form['name'] = array(
'#type' => 'select',
'#title' => t('Select Node'),
'#options' => node_type_get_names(),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Download CSV file'),
);
return $form;
}

function newtest_csv_export_form_submit($form,&$form_state) {

newtest_csv_export_file($form_state);
}

function newtest_csv_export_file($form_state) {
$filename = 'nodes.csv';
drupal_add_http_header('Content-Type', 'application/csv; utf-8');
drupal_add_http_header('Content-Disposition', 'attachement; filename = nodes.csv');
$fp = fopen('public://MyCSV/nodes.csv', 'w');
foreach($result as $data){
fputcsv($fp, $data);
}
$dataset_directory = variable_get('file_public_path', conf_path() . '/files') . "/MyCSV/";
file_prepare_directory($dataset_directory, FILE_CREATE_DIRECTORY);
drupal_exit();
}