你好,我很新的PHP,我想讓網頁的用戶上傳一個csv文件,然後將行存儲到MySQL行。除了cvs文件在每行末尾留下逗號,導致最後一個單元格和下一行的第一個單元格合併之外,一切都很好。我哪裏錯了?謝謝!PHP讀取cvs文件,當逗號被忽略
PHP文件時,會在形式執行提交:
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$file_handle = fopen($target_file, "r");
while (!feof($file_handle)) {
$line_of_text = fgetcsv($file_handle, 1024);
//print $line_of_text[0] . $line_of_text[1]. $line_of_text[2] . "<BR>";
$arrlength = count($line_of_text);
for($x = 0; $x < $arrlength; $x = $x + 1){
echo $x. " ".$line_of_text[$x]. "<br>";
}
for($x = 7; $x < $arrlength; $x = $x + 6) {
$insertSQL = sprintf("INSERT INTO `tooneate_MyTrivia`.`Question` (
`CategoryId`,
`Question`,
`Group`,
`AnsOne`,
`AnsTwo`,
`AnsThree`,
`AnsFour`,
`CorrectAns`) VALUES (%d, %s, %s, %s, %s, %s, %s, %d)",
GetSQLValueString($line_of_text[$x], "int"),//CatId
GetSQLValueString($line_of_text[$x+1], "text"),//Question
GetSQLValueString("1", "text"),//Group
GetSQLValueString($line_of_text[$x+2], "text"),//AnsOne
GetSQLValueString($line_of_text[$x+3], "text"),//AnsTwo
GetSQLValueString($line_of_text[$x+4], "text"),//AnsThree
GetSQLValueString($line_of_text[$x+5], "text"),//AnsFour
GetSQLValueString($line_of_text[$x+6], "int"));//CorrectAns
echo $insertSQL;
echo "<br>";
mysql_select_db($database_TooNeate, $TooNeate);
$Result1 = mysql_query($insertSQL, $TooNeate) or die(mysql_error());
$insertGoTo = "MyTrivia.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
}
fclose($file_handle);
這裏是正在上傳的文件示例:
類別編號,問,答一句,答二,回答三個,答案四,正確答案
1,是CSV文件的工作?,是,否,也許,ehhh,1
1,這是非常酷黨?,是,否,也許,ehhh,4
在細胞「正確答案」上面的CSV文件合併到下一個「1」,「1」和「1」
謝謝!
你fgetcsv看起來沒有足夠的參數。 $ line_of_text = fgetcsv($ file_handle,1024,「,」); – TBridges 2015-03-19 01:39:33
您是否嘗試過啓用'auto_detect_line_endings',正如'fgetcsv'手冊所示? – CBroe 2015-03-19 01:41:53