我想阅读上传的csv文件的内容,然后在将其转换为utf-8编码后将其写回文件
我发现我可以使用以下代码转换编码 iconv('希伯来',' utf-8',$ str);
我使用以下代码逐行读取csv文件,并在转换后将其写回。 主要思想是通过逐行阅读来导入csv,但是基于文件的包含有一些希伯来语的问题。
所以使用下面的代码检查编码是utf-8还是utf-16le(windows),然后相应地转换数据。如果数据与其中一个编码不匹配,则使用iconv('希伯来语',' utf-8',$ str);但它不起作用
public function actionUpload()
{
$params = $_FILES['uploadFile'];
if($params)
{
$data = array();
$model = new UploadForm();
$model->uploadFile = $_FILES['uploadFile'];
$file = UploadedFile::getInstanceByname('uploadFile');
$inputFileName = $model->getpath($file,$data);
// Read your Excel workbook
try
{
$inputFileType = \PHPExcel_IOFactory::identify($inputFileName['link']);
$objReader = \PHPExcel_IOFactory::createReader($inputFileType);
if($inputFileType == 'CSV')
{
if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-8'))
{
$objReader->setInputEncoding('UTF-8');
}
else if (mb_check_encoding(file_get_contents($inputFileName['link']), 'UTF-16le'))
{
$objReader->setInputEncoding('UTF-16le');
}
else
{
$handle = fopen("test.csv", "r+");
if ($handle)
{
while (($line = fgets($handle)) !== false)
{
$newLine = iconv('hebrew', 'utf-8', $line);
fwrite($handle , $newLine);
}
fclose($handle);
}
else
{
// error opening the file.
}
$objReader->setInputEncoding('UTF-8');
}
}
$objPHPExcel = $objReader->load($inputFileName['link']);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName['link'],PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$fileData = array();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++)
{
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
array_push($fileData,$rowData[0]);
// Insert row data array into your database of choice here
}
return $fileData;
}
}
答案 0 :(得分:0)
PHP文档注释中有一个hack,用于将希伯来语编码转换为utf-8