0

In my Magento store, I am facing one issue that I am not able to import the product with special characters. For the CSV base I have followed the below tutorial. Can anyone please help me how can I encode with UTF-8 in CSV when writing it?

https://www.rakeshjesadiya.com/how-to-create-a-csv-file-to-download-using-magento-2/

Note: It's custom product import

2 Answers 2

3

You can convert your string to UTF-8 by using default PHP function.

mb_convert_encoding(string, encode_type)

Please check below example for more details.

$products[] = array(1,'Test 1','test 1',100);
$products[] = array(2,'Test 2','test 2',299);

foreach ($products as $item) {
     $itemData = [];
     $itemData[] = mb_convert_encoding($item[0], "UTF-8");
     $itemData[] = mb_convert_encoding($item[1], "UTF-8");
     $itemData[] = mb_convert_encoding($item[2], "UTF-8");
     $itemData[] = mb_convert_encoding($item[3], "UTF-8");
     $stream->writeCsv($itemData);
}

I hope this will help you.

1
2

Please follow the below code snippets,

        //Declare column and data
        $result[] = [
        'Column1',
        'Column2'
        ];
        
        $result[] = [
        'data01',
        'data02'
        ];
        
    
        $varDir = $this->_filesystem->getDirectoryRead(DirectoryList::VAR_DIR)->getAbsolutePath();
        $directory = $this->_filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $tmpFolder = 'customfolder';
        $directory->create($tmpFolder);

        $filename = "filename" . ".csv";
        
        if ($this->_file->isExists($varDir . $tmpFolder . DIRECTORY_SEPARATOR . $filename)) {
            $this->_file->deleteFile($varDir . $tmpFolder . DIRECTORY_SEPARATOR . $filename);
        }

        $filePath = $varDir . $tmpFolder . DIRECTORY_SEPARATOR . $filename;

        $this->csvWriter
            ->saveData(
                $filePath,
                $result
            );

and add dependency to your constructor,

        use Magento\Framework\Filesystem;
        use Magento\Framework\App\Filesystem\DirectoryList;
        use Magento\Framework\Filesystem\Driver\File;
        use Magento\Framework\File\Csv;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.