简体   繁体   中英

Upload a CSV file to MySQL with utf-8 encoding in php

I'm trying to upload a csv file to mySQL with this code:

if(isset($_POST["submit"]))
{


header('Content-Type: text/html; charset=utf-8');


$ftype  = $_FILES['file']['type'];

if($ftype == "application/vnd.ms-excel" || $ftype == "APPLICATION/VND.MS-EXCEL"){ 


$file = $_FILES['file']['tmp_name'];



$handle = fopen("$file", "r");

$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{

  htmlspecialchars($filesop, ENT_NOQUOTES, "UTF-8");



$fname = $filesop[0];
$lname = $filesop[1];
$famif = $filesop[2];
$lnmvb = $filesop[3];


$sql = mysql_query("insert into Alfon (Name,phone,Address,House,Identification) values ('$fname','$lname','$famif','$lnmvb','')");
$c = $c + 1;
}
if($sql){
echo "הקובץ הועלה בהצלחה 
$fname
$lname
$famif
$lnmvb
$file
";
} 
else
{
echo "שגיאה! אנא פרמט לסוג הקובץ הנכון.";
}

} else { echo "שגיאה בפורמט הקובץ $ftype";}

}


?>
<!DOCTYPE html>

        <title>ספר טלפונים דיגיטלי</title>
<body>
<form enctype="multipart/form-data" accept-charset="utf-8" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150" accept-charset="utf-8">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="submit" value="submit">Upload</button>
</form>
</body>
</html>

The problem is that the data goes to a database other than the Hebrew text that became question marks (?), What can you do to encode the text into Hebrew ? I will thank you if you answer my question and help me!

(I would like to emphasize that text in English or numbers do go up to a valid database, only the Hebrew text goes wrong ...)

Use LOAD DATA INFILE , and be sure to include CHARACTER SET utf8mb4 .

That is, you can throw away all of that PHP code, replacing it with this one MySQL command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM