天天看點

mysql 導入 csv utf-8_将CSV檔案導入MySQL資料庫時,UTF-8字元串無效

mysql 導入 csv utf-8_将CSV檔案導入MySQL資料庫時,UTF-8字元串無效

I'm trying to import CSV into my MySQL database using this code:

I get the CSV file from post.

//conexiones, conexiones everywhere

ini_set('display_errors', 1);

error_reporting(E_ALL);

$db_host = 'localhost';

$db_user = 'root';

$db_pass = 'password';

$database = 'test';

$table = 'csvtable';

if ([email protected]_connect($db_host, $db_user, $db_pass))

die("No se pudo establecer conexión a la base de datos");

if ([email protected]_select_db($database))

die("base de datos no existe");

if(isset($_POST['submit']))

{

//Aquí es donde seleccionamos nuestro csv

$fname = $_FILES['sel_file']['name'];

echo 'Cargando nombre del archivo: '.$fname.'

';

$chk_ext = explode(".",$fname);

if(strtolower(end($chk_ext)) == "csv")

{

//si es correcto, entonces damos permisos de lectura para subir

$filename = $_FILES['sel_file']['tmp_name'];

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

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)

{

//Insertamos los datos con los valores...

$sql = "INSERT into csvtable(id, example, example2) values('$data[0]','$data[1]','$data[2]'";

mysql_query($sql) or die('Error: '.mysql_error());

}

//cerramos la lectura del archivo "abrir archivo" con un "cerrar archivo"

fclose($handle);

echo "Importación exitosa!";

}

else

{

//si aparece esto es posible que el archivo no tenga el formato adecuado, inclusive cuando es cvs, revisarlo para

//ver si esta separado por " , "

echo "Archivo invalido!";

}

}

?>

The problem is that I have words like Sol·licitud or Accés and I'm getting this error:

Error: Invalid utf8 character string: 'Sol\xB7licitant'

Could you help me guys?

解決方案

Dont know if this work for this case, but when I have text files showing wrong accents I just use UltraEdit or Notepad++ to change the Enconde to UTF-8

mysql 導入 csv utf-8_将CSV檔案導入MySQL資料庫時,UTF-8字元串無效