我想使用cakephp將數據從csv導入到mysql表。
當我運行該函數時,它將空值放入我的表中,我相信它是我的$ data數組的格式,這裏是我的代碼。使用cakephp將數據從csv導入到mysql
var $name = 'ScWidths';
var $scaffold;
/*
function import() {
$messages = $this->ScWidth->import('scwidths.csv');
$this->set('messages', $messages);
}
*/
function import() {
// to avoid having to tweak the contents of
// $data you should use your db field name as the heading name
// eg: Post.id, Post.title, Post.description
// set the filename to read CSV from
$filename = TMP . 'uploads' . DS . 'Sc_widths' . DS . 'scwidths.csv';
// open the file
$handle = fopen($filename, "r");
// read the 1st row as headings
$header = fgetcsv($handle);
// create a message container
$return = array(
'messages' => array(),
'errors' => array(),
);
// read each data row in the file
$i = 0;
while (($row = fgetcsv($handle)) !== FALSE) {
$i++;
$data = array();
// for each header field
foreach ($header as $k=>$head) {
// get the data field from Model.field
if (strpos($head,'.')!==false) {
$h = explode('.',$head);
#die(debug($h));
$data[$h[0]][$h[1]]=isset($row[$k]) ? $row[$k] : '';
}
// get the data field from field
else {
$data['ScWidth'][$head]=isset($row[$k]) ? $row[$k]: '';
}
}
$data['ScWidth']['section_id']=1;
$this->ScWidth->create();
// success or not :/
if ($this->ScWidth->save($data)) {
echo "success";
}
}
// close the file
fclose($handle);
// return the messages
//return $return;
}
我調試點返回數組
array(
'ScWidths' => array(
'chainage' => '0'
),
'Left_side' => '3.7'
),
'right_side' => '3.7'
),
'section_id' => (int) 1
)
)
錯誤日誌即時得到,
什麼...
我相信我的下一個錯誤是我的保存方法。
這裏是我的數據文件,只是incase。
ScWidths.chainage,ScWidths.Left_side,ScWidths.right_side
0,3.7,3.7
10,3.7,3.7
20,3.7,3.7
30,3.7,3.7
40,3.7,3.7
50,3.7,3.7
60,3.7,3.7
70,3.7,3.7
80,3.7,3.7
糾正我的代碼,這是工作100%,如果有人需要一個例子:)
你能請分配採樣xls文件? – Anubhav