假設我有一個CSV這樣的:Drupal 7 |導入CSV,逐行,到自定義表
value1,value2
value1,value2
,並與兩列
column1|column2
我怎麼能編程導入CSV到表的表?
假設我有一個CSV這樣的:Drupal 7 |導入CSV,逐行,到自定義表
value1,value2
value1,value2
,並與兩列
column1|column2
我怎麼能編程導入CSV到表的表?
@ 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);
或添加數據到數據庫並顯示到屏幕上沒有第二個數據庫適應兩擊中。
該模塊可以幫助你 https://www.drupal.org/sandbox/draenen/2442165 它需要飼料,但其擴展與自定義表(非Drupal的實體)工作
這是我想出來的 - 我不是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