假设我有这样的CSV:
value1,value2
value1,value2
和一个包含两列的表
column1|column2
如何以编程方式将CSV导入表格?
答案 0 :(得分:1)
这就是我的想法 - 我不是PHP专家 - 它看起来并不漂亮 - 但它确实有效!
$handle = fopen('/path/to/file/filename.csv', 'r');
$row = fgetcsv($handle);
for ($e = 0; $row = fgetcsv($handle); $e++) {
$record = array();
foreach ($row as $field) {
$record[] = $field;
}
db_insert('your_db_table')
->fields(array(
'column1' => $record[0],
'column2' => $record[1]
))
->execute();
}
fclose($handle);
该表将如下所示:
column1|column2
---------------
value1|value2
value1|value2
答案 1 :(得分:1)
@ erier的回答非常好,将完成工作。
当问题用Drupal 7标记时,我想我会提交一个Drupal自定义模块方法,调整@ erier的答案并对其进行美化。
有关自定义模块的基础知识,您可以看到这个简单的示例。
function custom_module_form($form, &$form_state) {
$form['csv_upload'] = array(
'#type' => 'file',
'#title' => t('Choose a file'),
'#title_display' => 'invisible',
'#size' => 22,
'#upload_validators' => array('file_clean_name' => array()),
);
$form['upload'] = array(
'#type' => 'submit',
'#value' => 'Upload',
);
}
function custom_module_form_validate($form, &$form_state) {
$validators = array('file_validate_extensions' => array('csv'));
// Check for a new uploaded file.
$file = file_save_upload('csv_upload', $validators);
//$file = $form_state['values']['csv_upload'];
if (isset($file)) {
// File upload was attempted.
if ($file) {
// Put the temporary file in form_values so we can save it on submit.
$form_state['values']['csv_upload_file'] = $file;
}
else {
// File upload failed.
form_set_error('csv_upload', t('The file could not be uploaded.'));
}
}
}
function custom_module_submit($form, &$form_state) {
$file = $form_state['values']['csv_upload_file'];
$file->status = FILE_STATUS_PERMANENT;
$file->filename = str_replace(' ', '_', $file->filename);
file_save($file);
$csv_file = file_load($file->fid);
$file = fopen($csv_file->uri, "r");
while(! feof($file))
{
$customer = fgetcsv($file));
db_insert('your_db_table')
->fields(array(
'column1' => $customer[0],
'column2' => $customer[1]
))
->execute();
}
fclose($file);
drupal_set_message('CSV data added to the database');
}
function file_clean_name($file) {
$file->filename = str_replace(' ', '_', $file->filename);
}
假设您的问题是关于数据库表的。
如果你想进入一个html表,你可以在$csv_file = file_load($file->fid);
之后调整提交函数:
$headers = array('column 1', 'column 2');
$rows = array();
$file = fopen("contacts.csv","r");
while(! feof($file))
{
$customer = fgetcsv($file));
$rows[] = array($customer[0], $customer[1]);
}
fclose($file);
return theme('table', array('header' => $headers, 'rows' => $rows);
或者通过将数据添加到数据库并在没有第二次数据库命中的情况下显示到屏幕来调整这两者。
答案 2 :(得分:0)
此模块可能对您有所帮助 https://www.drupal.org/sandbox/draenen/2442165 它需要Feeds,但它扩展它以使用自定义表(非drupal实体)