Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP字符集存在问题_Php_Mysql - Fatal编程技术网

PHP字符集存在问题

PHP字符集存在问题,php,mysql,Php,Mysql,我通常不会在字符集上出现问题,但这一次我不知道问题出在哪里 function categories($host, $user, $pw, $bd){ $file_handle = fopen("categories.csv", "rb"); $mysqli = new mysqli($host, $user, $pw, $bd); $mysqli->set_charset('utf8'); while (!feof($file_handle) ) {

我通常不会在字符集上出现问题,但这一次我不知道问题出在哪里

function categories($host, $user, $pw, $bd){
    $file_handle = fopen("categories.csv", "rb");

    $mysqli = new mysqli($host, $user, $pw, $bd);
    $mysqli->set_charset('utf8');

    while (!feof($file_handle) ) {
        $line_of_text = fgets($file_handle);
        $parts = explode(';', $line_of_text);

        $description = $parts[1];
        $parent = $parts[2];

        $query = $mysqli->prepare("INSERT INTO categories (`description`, parent) VALUES(?, ?)");
        $query->bind_param("si", $description, $parent);
        $query->execute();
    }
    fclose($file_handle);   
}
我对其他文件有相同的代码,比如国家,等等,我对字符集没有问题。 如您所见,我一如既往地使用
$mysqli->set_字符集('utf8')代码。如果我回显
$description
变量,我会得到正确的字符(它们大部分是葡萄牙语)

这就是我迄今为止所尝试的:

$query = $mysqli->prepare("SET NAMES 'utf8'"); // inside the function
$query->execute();

header('Content-Type: text/html; charset=utf-8'); // in the top of the page
但它继续在数据库中添加诸如:Feij?o(Feijão)、Ch?s(Chás)等词

我确实觉得这很愚蠢,因为我确实在另一个表中插入了带有口音的国家名称,就像我说的,没有任何问题

猜猜看

编辑:使用utf8\u编码解决

$query->bind_param("si", utf8_encode($description), $parent);

问题可能出在文件“categories.csv”中,它不能是UTF-8

要将文件从“ASCII”转换为UTF-8,可以使用

iconv -f WINDOWS-1252 -t UTF-8 categories.csv

确保PHP设置为处理utf-8:
header('Content-Type:text/html;charset=utf-8')。您也可以尝试:
setlocale(LC_ALL,'葡萄牙语_葡萄牙语.1252')检查字段、表格和数据库字符集是否也是
utf-8
,不仅仅是您的连接。我用记事本++打开categories.csv,它的编码是“ANSII”,如果我将其更改为utf-8,它将使用
此。尝试使用
iconv('UTF-8','Windows-1252',$str')转换CSV的每个字段
@MarceloPascual I receive(对于具有特殊字符的字段):在输入字符串中检测到非法字符您可能应该在从php读取文件之前转换该文件(请参阅我更新的答案…)。