douhuan6065 2018-01-24 05:20
浏览 50

fgetcsv插入字符像?????? 进入mysql数据库[关闭]

I am making a little php application with fgetcsv for inserting multiple record into mysql database. It works fine with english charactor. But when I trying to add foreign language like bengali or hindi it inserts ????? into mysql database.

Here my mysql database table structure

enter image description here

Here a result for foreign language character

enter image description here

Here my application code

<?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);

Here the data csv file I am using and some foreign character here শ্যামল অসিম কার্তিক

Any suggestion or solution will highly appreciate. Thank you.

  • 写回答

1条回答 默认 最新

  • drgdn82648 2018-01-24 05:29
    关注

    Use fgets() get file all string in a variable, then use mb_convert_encoding() to convert encoding, then str_getcsv() convert string to array.

    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);
    

    the from array you can save it in db.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。