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
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;
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.
-
Hello @Siv, is it working for you ?Mohammad Bharmal– Mohammad Bharmal2023年01月07日 11:07:01 +00:00Commented Jan 7, 2023 at 11:07