1

I am using a php class, where it writes and stores CSV files in the folder of my site. But am unable to write UTF-8 characters of different languages which is present in my database.

I am using the following class to write csv file. How can I add support to write utf-8 characters to this class. I have tried google and other places, but no finding any luck.

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;
    }
    }

After browsing from so many days, I found that I would have to need to add BOM to fix UTF-8 in Excel, but was unseccessful in adding to this class.

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

1 Answer 1

1

Add it here:

$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));
Sign up to request clarification or add additional context in comments.

8 Comments

thanks for your immediate answer, still gives me ???? ???? for non-english characters
Are you sure that you call putRecord() with an array that is all UTF-8?
Yes, I use putRecord() like this.... $csvWriter->putRecord(array('Phone', 'Name', 'Product', 'Delivered on', 'No of Products', 'Remarks' ));
Yes, but a line that has non-english characters. Is that UTF-8 for sure?
yes, and I can also see it in mysql field. Perfectly saved. and also I tried with this... fputs($this->fileHandle, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.