4

我收到了这个有很多问题的项目。其中之一是最终用户正在上传一个 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');在文件的顶部。

4

3 回答 3

4

我在使用 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);
于 2012-06-15T17:26:01.967 回答
0

我认为你写的有问题echo "<p>$d</p>";。我认为这应该是

echo "<p>".$d."</p>";
于 2012-06-15T17:23:08.630 回答
0

我拿走了你的代码并使用变量让它工作。

$string = "Rock/Classic 80’s-90’s";
$replace = "’";
$string = str_replace($replace, "", $string);
echo "<p>$string</p>";
于 2012-06-15T17:31:07.427 回答