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

asked Jan 6, 2023 at 3:06

2 Answers 2

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;
answered Jan 6, 2023 at 6:39
2

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.

answered Jan 6, 2023 at 10:03
1
  • Hello @Siv, is it working for you ? Commented Jan 7, 2023 at 11:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.