gpt4 book ai didi

PHP 字符集有问题

转载 作者:行者123 更新时间:2023-11-29 08:16:28 25 4
gpt4 key购买 nike

我通常不会遇到字符集问题,但这次我不明白问题出在哪里。

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_charset('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_encode。

$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 字符集有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20523315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com