【问题标题】:Writing UTF-8 fields from mysql in PHP to CSV format以 PHP 将 mysql 中的 UTF-8 字段写入 CSV 格式
【发布时间】:2014-04-02 15:40:44
【问题描述】:

我正在使用php class,它将CSV files 写入并存储在我网站的文件夹中。但我无法编写数据库中存在的不同语言的UTF-8 字符。

我正在使用以下类来编写 csv 文件。如何添加支持以将 utf-8 字符写入此类。我试过谷歌和其他地方,但没有找到任何运气。

class b3rtCSVWriter
{
var $filename;
var $delimiter;

var $fileHandle;
var $fileBuffer;
var $fileBufferSize;

var $errorList;

/*function b3rtCSVWriter()
    {
    }*/

    function __construct()
    {
    $this->filename = '';
    $this->delimiter = ',';

    $this->fileHandle = NULL;
    $this->fileBuffer = '';
    $this->fileBufferSize = 4096;

    $this->errorList = array();
    }

    function __destruct()
    {
    $this->closeFile();
    }

    function setFilename($filename)
    {
    $this->filename = $filename;

    return $this->openFile();
    }

    function setDelimiter($delimiter)
    {
    if (strlen($delimiter) != 1)
        {
        $this->setError('Invalid delimiter');
        return FALSE;
        }

    $this->delimiter = $delimiter;
    return TRUE;
    }

    function getErrors()
    {
    return $this->errorList;
    }

    function putRecord($recordData)
    {
    if ($this->errorList)
        return ($this->fileHandle === NULL ? '' : FALSE);

    $rowBuffer = '';

    // Check if recordData is an array
    if (isset($recordData) && is_array($recordData))
        {
        $currentFieldIndex = -1;
        $lastFieldIndex = count($recordData) - 1;

        // Loop through every array item
        foreach($recordData as $recordValue)
            {
            $currentFieldIndex++;
            $isQuotedField = FALSE;

            // Set isQuotedField if a " is present and replace " with ""
            if (strpos($recordValue, '"') !== FALSE)
                {
                $isQuotedField = TRUE;
                $recordValue = str_replace('"', '""', $recordValue);
                }

            // Set isQuotedField if a delimiter or newline is present
            if ((strpos($recordValue, $this->delimiter) !== FALSE) ||
                (strpos($recordValue, "\n") !== FALSE))
                $isQuotedField = TRUE;

            // Put field inside " if isQuotedField is set
            if ($isQuotedField)
                $recordValue = '"'.$recordValue.'"';

            // Add recordValue to rowBuffer and, if not at last field, a delimiter
            $rowBuffer .= $recordValue .
                ($currentFieldIndex != $lastFieldIndex ? $this->delimiter : '');
            }
        }

    // Add EOL to rowBuffer, even when it's empty
    $rowBuffer .= "\r\n";

    // If no file is currently open, return rowBuffer as is
    if ($this->fileHandle === NULL)
        return $rowBuffer;
    else // Else write rowBuffer to file
        return $this->writeFile($rowBuffer);
    }

    function openFile()
    {
    $this->closeFile();

    if ($this->filename == '')
        $this->setError('Invalid filename');

    if ($this->errorList)
        return FALSE;

    $this->fileHandle = @fopen($this->filename, 'w');
    if (!$this->fileHandle)
        {
        $this->setError('Could not open file');
        $this->fileHandle = NULL;
        return FALSE;
        }

    if (!flock($this->fileHandle, LOCK_EX))
        {
        $this->setError('Could not lock file');
        $this->closeFile();
        return FALSE;
        }

    return TRUE;
    }

    function writeFile($toWrite, $forceWrite = FALSE)
    {
    if ($this->fileHandle === NULL)
        {
        $this->setError('No file specified');
        return FALSE;
        }

    $this->fileBuffer .= $toWrite;

    if ($forceWrite || (strlen($this->fileBuffer) > $this->fileBufferSize))
        {
        if (@fwrite($this->fileHandle, $this->fileBuffer, strlen($this->fileBuffer)) === FALSE)
            {
            $this->setError('Could not write to file');
            return FALSE;
            }

        $this->fileBuffer = '';
        }

    return TRUE;
    }

    function closeFile()
    {
    if (is_resource($this->fileHandle))
        {
        // Force buffer to be written
        $this->writeFile('', TRUE);

        if (!fflush($this->fileHandle))
            $this->setError('Could not flush output to file');
        if (!flock($this->fileHandle, LOCK_UN))
            $this->setError('Could not unlock file');
        if(!@fclose($this->fileHandle))
            $this->setError('Could not close file');
        }

    $this->fileHandle = NULL;
    }

    function setError($error)
    {
    $this->errorList[] = $error;
    }
    }

浏览了这么多天,发现需要添加BOM来修复Excel中的UTF-8,但是添加到这个类中不成功。

    $fp = fopen('php://output', 'w');
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fclose($fp);

【问题讨论】:

    标签: php csv export-to-csv


    【解决方案1】:

    在此处添加:

    $this->fileHandle = @fopen($this->filename, 'w');
    if (!$this->fileHandle)
        {
        $this->setError('Could not open file');
        $this->fileHandle = NULL;
        return FALSE;
        }
    fputs($this->fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));
    

    【讨论】:

    • 感谢您的即时答复,仍然给我???? ???对于非英文字符
    • 您确定调用putRecord() 时使用了一个全是UTF-8 的数组吗?
    • 是的,我这样使用 putRecord() ......$csvWriter->putRecord(array('Phone', 'Name', 'Product', 'Delivered on', 'No of Products', 'Remarks' ));
    • 是的,但是一行包含非英文字符。确定是 UTF-8 吗?
    • 是的,我也可以在mysql字段中看到。完美保存。我也试过这个......fputs($this->fileHandle, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    猜你喜欢
    • 2014-02-03
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多