我接到的这个项目有很多问题。其中之一是最终用户正在上传一个 CSV 文件,该文件直接从 MS Access 导出到他们的 Web 服务器上的目录中。下一步是截断几个数据库表,然后将 CSV 中的所有记录插入数据库。
但是,MS Access 用于撇号的撇号字符存在问题。它不是单引号 ',也不是双引号 "。它是一个撇号。像这样:
"Rock/Classic 80’s-90’s"
现在,我已经在我的 PHP 中尝试了以下方法来去除它们:
$d = str_replace("’", "", $d);
$d = str_replace(array("'", "\'", "\’", "’"), "", $d);
但是,这似乎行不通。事实上,当基于此数据运行 SQL 查询时,它似乎总是以某种方式将 ’ 转换为 ' 而没有将它们剥离,然后导致 SQL 错误,因为它认为字符串已提前终止。
这是我正在使用的代码块之一:
$band_insert = "INSERT INTO `schedule` (`Band`, `Date`, `Genre`, `Club`, `Location`, `Venue`, `Time`) VALUES ( '%s', '%s', '%s', '%s', '%s', '%s', '%s' )";
$result = $mysqli->query('TRUNCATE TABLE `schedule`');
if(!$result) die('Truncate error');
if( ($handle=fopen('./export/schedule.csv', 'r')) !== FALSE)
{
while( ($data=fgetcsv($handle, 1000, ',', '"', '\\')) !== FALSE )
{
foreach($data as $d)
{
$d = str_replace("’", "", $d);
# For debugging purposes only
echo "<p>$d</p>";
}
$sql = sprintf($band_insert, $data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6]);
#$sql = $mysqli->real_escape_string($sql);
$result = $mysqli->query($sql);
if( ! $result ) $log[] = lg("Unable to perform query ($mysqli->errno): $mysqli->error");
}
$log[] = lg("Successful upload (".date("Y-m-d").").");
fclose($handle);
}
问题变成了,为什么这不起作用?当我回显 $d 值时,它会打印一个 ?在一个广场上。即使在文件顶部有 header('Content-type: text/html; charset=utf-8');
。
最佳答案
我在使用 Access 和 Excel 时遇到了一些类似的障碍,并使用我在某处捡到的这个来删除 MS 字符(所以这一切都归功于它的原作者)。也许您可以按原样使用它,或者相应地进行调整:
// First, replace UTF-8 characters.
$text = str_replace(
array("\xe2\x80\x98", "\xe2\x80\x99", "\xe2\x80\x9c", "\xe2\x80\x9d", "\xe2\x80\x93", "\xe2\x80\x94", "\xe2\x80\xa6"),
array("'", "'", '"', '"', '-', '--', '...'),
$text);
// Next, either REPLACE their Windows-1252 equivalents.
$text = str_replace(
array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
array("'", "'", '"', '"', '-', '--', '...'),
$text);
// OR, STRIP their Windows-1252 equivalents.
$text = str_replace(
array(chr(145), chr(146), chr(147), chr(148), chr(150), chr(151), chr(133)),
array('', '', '', '', '', '', ''),
$text);
关于php - 如何去除 PHP 中的特殊引号字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11055375/