fgetcsv插入字符像??????进入mysql数据库

时间:2018-01-24 05:20:53

标签: php mysql database fgetcsv

我正在用fgetcsv创建一个小的php应用程序,用于将多个记录插入到mysql数据库中。它适用于英语字符。但是当我试图添加像bengali或印地语这样的外语时,它会插入?????进入mysql数据库。

这里是我的mysql数据库表结构

enter image description here

这是外语字符的结果

enter image description here

这是我的应用程序代码

<?php

    // Use PDO to connect to the DB
    $dsn = 'mysql:dbname=phpcsv_db;host=localhost';
    $user = 'root';
    $password = '';

    try {
        $dbh = new PDO($dsn, $user, $password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }

    $handle = fopen('data.csv', "r");

    for($i =1;($data = fgetcsv($handle, 10000, ",")) !== FALSE; $i++) {
        // The query uses placeholders for data
        $sql = "INSERT INTO phpcsv
                    (name,email,phone) 
                VALUES
                    (:name,:email,:phone)";
        $sth = $dbh->prepare($sql);

        // The data is bound to the placeholders
        $sth->bindParam(':name', $data[0]);
        $sth->bindParam(':email', $data[1]);
        $sth->bindParam(':phone', $data[2]);

        // The row is actually inserted here
        $sth->execute();
        $sth->closeCursor();
    }
ini_set('auto_detect_line_endings',FALSE);

fclose($handle);

这里我使用的data csv file和一些外国人在这里শ্যামলমলিমমার্তিক

任何建议或解决方案都将非常感谢。谢谢。

1 个答案:

答案 0 :(得分:1)

使用fgets()获取文件变量中的所有字符串,然后使用mb_convert_encoding()转换编码,然后str_getcsv()将字符串转换为数组。

if (($handle = fopen("books.csv", "r")) === FALSE)
    throw new Exception("Couldn't open books.csv");

$data = "";

// get file all strin in data
while (!feof($handle)) {
    $data .= fgets($handle, 5000);
}

// convert encoding
$data = mb_convert_encoding($data, "UTF-8", "auto");

// str_getcsv
$array = str_getcsv($data);

from数组,你可以将其保存在db。