Php fgetcsv utf 8

UTF-8 problems while reading CSV file with fgetcsv

I try to read a CSV and echo the content. But the content displays the characters wrong. Mäx Müstermänn -> Mäx Müstermänn Encoding of the CSV file is UTF-8 without BOM (checked with Notepad++). This is the content of the CSV file: «Mäx»;»Müstermänn» My PHP script

     First nameLast name'; while ($data = fgetcsv ($handle, 1000, ";")) < $num = count ($data); for ($c=0; $c < $num; $c++) < // output data echo "$data[$c]"; > echo ""; > ?>  

I tried to use setlocale(LC_ALL, ‘de_DE.utf8′); as suggested here without success. The content is still wrong displayed. What I’m missing? Edit: An echo mb_detect_encoding($data[$c],’UTF-8’); gives me UTF-8 UTF-8. echo file_get_contents(«specialchars.csv»); gives me «Mäx»;»Müstermänn» . And

print_r(str_getcsv(reset(explode("\n", file_get_contents("specialchars.csv"))), ';')) 

What happens when you do echo file_get_contents(«specialchars.csv»)? What happens when you do print_r(str_getcsv(reset(explode(«\n», file_get_contents(«specialchars.csv»))), ‘;’))?

6 Answers 6

First nameLast name'; while ($data = fgetcsv ($handle, 1000, ";")) < $data = array_map("utf8_encode", $data); //added $num = count ($data); for ($c=0; $c < $num; $c++) < // output data echo "$data[$c]"; > echo ""; > ?> 

@robssanches the above code work for only alphabets type of words(character) but it does not work with other languages for e.g Chinese, Hindi, Hebrew etc.. etc

This worked for me. So sad, that this helpful line is missing in official documentation de.php.net/manual/de/function.fgetcsv.php

I am having some trouble with this solution. Some characters as ’ (right single quote mark) and … (ellipsis) are not working with utf8_encode

Encountered similar problem: parsing CSV file with special characters like é, è, ö etc .

The following worked fine for me:

To represent the characters correctly on the html page, the header was needed :

header('Content-Type: text/html; charset=UTF-8'); 

In order to parse every character correctly, I used:

Dont forget to use in all following string operations the ‘Multibyte String Functions’, like:

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string.

So this solution helped me a lot:

/** * getting CSV array with UTF-8 encoding * * @param resource &$handle * @param integer $length * @param string $separator * * @return array|false */ private function fgetcsvUTF8(&$handle, $length, $separator = ';') < if (($buffer = fgets($handle, $length)) !== false) < $buffer = $this->autoUTF($buffer); return str_getcsv($buffer, $separator); > return false; > /** * automatic convertion windows-1250 and iso-8859-2 info utf-8 string * * @param string $s * * @return string */ private function autoUTF($s) < // detect UTF-8 if (preg_match('#[\x80-\x\x-\x]#u', $s)) return $s; // detect WINDOWS-1250 if (preg_match('#[\x7F-\x9F\xBC]#', $s)) return iconv('WINDOWS-1250', 'UTF-8', $s); // assume ISO-8859-2 return iconv('ISO-8859-2', 'UTF-8', $s); > 

Response to @manvel’s answer — use str_getcsv instead of explode — because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others 

explode will explode string into parts:

some nice value "and here comes combinated value" and some others 

but str_getcsv will explode string into parts:

some nice value and;here;comes;combinated;value and some others 

Источник

fgetcsv

Подобно fgets () за исключением того, что fgetcsv () анализирует строку, которую он читает, для полей в CSV форматирует и возвращает массив,содержащий прочитанные поля.

Note:

Эта функция учитывает языковые настройки. Если LC_CTYPE , например, en_US.UTF-8 , файлы в однобайтовой кодировке могут быть неправильно прочитаны этой функцией.

Parameters

Действительный файловый указатель на файл, успешно открытый с помощью функций fopen () , popen () или fsockopen () .

Должен быть больше, чем самая длинная строка (в символах), которая может быть найдена в CSV-файле (с учетом символов конца строки). В противном случае строка разбивается на куски по length символов, если только разделение не произойдет внутри вложения.

Если этот параметр не указывать (или установить для него значение 0 или null в PHP 8.0.0 или более поздних версиях), максимальная длина строки не ограничивается, что немного медленнее.

Необязательный параметр separator устанавливает разделитель полей (только один однобайтовый символ).

Необязательный параметр enclosure устанавливает символ включения поля (только один однобайтовый символ).

Необязательный параметр escape устанавливает escape-символ (не более одного однобайтового символа). Пустая строка ( «» ) отключает собственный механизм выхода.

Примечание : Обычно символ enclosure внутри поля экранируется путем его удвоения; однако в качестве альтернативы можно использовать escape — символ. Таким образом, для значений параметров по умолчанию «» и \» имеют одно и то же значение. Помимо разрешения экранирования символа enclosure escape — символ не имеет особого значения, он даже не предназначен для экранирования самого себя.

Return Values

Возвращает индексированный массив, содержащий поля, прочитанные в случае успеха, или false в случае неудачи.

Note:

Пустая строка в CSV-файле будет возвращена как массив,состоящий из одного нулевого поля,и не будет рассматриваться как ошибка.

Примечание . Если PHP неправильно распознает окончания строк при чтении файлов на компьютере Macintosh или созданных им, включение параметра конфигурации времени выполнения auto_detect_line_endings может помочь решить проблему.

Changelog

Version Description
8.0.0 length теперь допускает значение NULL.
7.4.0 Параметр escape теперь также принимает пустую строку, чтобы отключить собственный механизм escape.

Examples

Пример # 1 Чтение и печать всего содержимого CSV-файла

 $row = 1; if (($handle = fopen("test.csv", "r")) !== FALSE) < while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) < $num = count($data); echo " 

$num fields in line $row:

\n"
; $row++; for ($c=0; $c < $num; $c++) < echo $data[$c] . "
\n"
; > > fclose($handle); > ?>

See Also

  • str_getcsv () — Преобразует строку CSV в массив
  • explode () — разбивает строку на строку
  • file () — считывает весь файл в массив
  • pack () — Упаковывает данные в двоичную строку
  • fputcsv () — Форматирует строку как CSV и записывает в указатель файла
PHP 8.2

(PHP 4 4.0.1,5,7,8)fflush Промывает вывод в файл Эта функция заставляет записать весь буферизованный вывод в ресурс,на который указывает файл stream.

(PHP 4,5,7,8)fgetc Получение символа из указателя файла Получение символа из заданного указателя файла.

(PHP 4,5,7)fgetss строка из указателя файла и зачистка HTML тегов Эта функция была УДАЛЕНА из PHP 7.3.0,и УДАЛЕНА в 8.0.0.

Источник

php fgetcsv — charset encoding problems

Using PHP 5.3 fgetcsv function, I am experiencing some problems due to encoding matters. Note that that file has spanish «special» latin characters like graphic accents á, é, í ï, etc. I get the CSV file exporting some structured data I have in an MS 2008 for Mac Excel file. If I open it with Mac OS X TextEdit application, everything seems to go perfect. But when I get down to my PHP program and try to read the CSV using that fgetcsv PHP function, I am not getting it to read properly the charset.

/** * @Route("/cvsLoad", name="_csv_load") * @Template() */ public function cvsLoadAction()< //setlocale(LC_ALL, 'es_ES.UTF-8'); $reader = new Reader($this->get('kernel')->getRootDir().'/../web/uploads/documents/question_images/2/41/masiva.csv'); $i = 1; $r = array("hhh" => $reader -> getAll()); return new Response(json_encode($r, 200)); > 

As you can see, I have tried also to use a setlocale to es_ES.UTF-8 . But nothing get it working. The read part comes here:

public function getRow() < if (($row = fgetcsv($this->_handle, 10000, $this->_delimiter)) !== false) < $this->_line++; return $this->_headers ? array_combine($this->_headers, $row) : $row; > else < return false; >> 

enter image description here

See what I get in the $row variable after each row reading: Those ? characters are supposed to be vowels with graphic accents on them. Any clue over there? Would it work if I used MS Excel for Windows? How can I know in run time the exact encoding of the file and set it before reading it? (For those spanish speakers, don’t get frightened with such awful medical stuff in those texts ;)).

Источник

PHP fgetcsv() not reading first UTF-8 character — alternatif using fgets

Based on the answer provided here by user user1830391: Some characters in CSV file are not read during PHP fgetcsv() I updated my following code to use fgets() instead of fgetcsv(). It fixed my first character issue. thats no longer a prob. but. what if the .csv file is seprated using ; instead of , Some fields will be wrapped using double quotes «», for example one of my rows is split onto 2 lines. quote opened in the last element of one line and closed at the end of the first element of the next line. There is an «enter»(/n) in that cell. how should i treat this using this code. fgetcsv catches elements within double quotes but i dont think fgets() does.

function runCSVtoArray() < // -->FOR IMPORT //Function that converts a CSV file to a PHP array. //echo 'Chargement du fichier CSV pour importation MYSQL. 
'; $readCharsPerLine = (JRequest::getVar('charsPerLine') > 0) ? JRequest::getVar('charsPerLine') : 1500; /* Import as of 2012-04-16 seem to have max 800chars per line. 1500 is alot of extra. */ ini_set("auto_detect_line_endings", true); iconv_set_encoding("internal_encoding", "UTF-8"); $openfile = $this->imp['importPath'].$this->imp['csvFileName']; if ( file_exists($openfile) ) < //echo 'Fichier CSV trouvé.
'; //echo 'Ouverture du fichier : '.$openfile.'
'; if (($handle = fopen($openfile, "r")) !== FALSE) < //echo 'Fichier CSV ouvert. Chargement en cours.
'; $row_i=0; $this->_importData = array(); /*while (($data = fgetcsv($handle, $readCharsPerLine, ";")) !== FALSE) '; echo ( (JRequest::getVar('encodeutf8')) && ( mb_detect_encoding($debugoutput, "UTF-8") == "UTF-8") ) ? utf8_encode($debugoutput) : $debugoutput.'
'; //Debug2 /* $num = count($data); if ($row_i==0) < // TITLE ROW $keyRow = array(); for ($c=0; $c < $num; $c++) < //Making title array with CSV first line //Key for colum if ( (JRequest::getVar('encodeutf8')) && ( mb_detect_encoding($data[$c], "UTF-8") == "UTF-8") ) < $data[$c] = utf8_encode($data[$c]); >if ($data[$c]!="") < $keyRow[$c]=trim($data[$c]); $keyRow[$c]=str_replace('GDWACCENT', '', $keyRow[$c]); //STRIP GDWACCENT, GDW uTF8 fgetcsv fix >else < $keyRow[$c]=''; >> > else < //VALUE ROW. for ($c=0; $c < $num; $c++) < $key = $keyRow[$c]; if ( (JRequest::getVar('encodeutf8')) && ( mb_detect_encoding($data[$c], "UTF-8") == "UTF-8") ) < $data[$c] = utf8_encode($data[$c]); $data[$c]=str_replace('GDWACCENT', '', $data[$c]); //STRIP GDWACCENT, GDW uTF8 fgetcsv fix >if ($data[$c]!="") < $this->_importData[$row_i][$key]=trim($data[$c]); $this->_importData[$row_i][$key]=str_replace('GDWACCENT', '', $this->_importData[$row_i][$key]); //STRIP GDWACCENT, GDW uTF8 fgetcsv fix > > > */ $row_i++; > //End while() //echo 'Chargement terminer. Sauvegarde en cours.
'; return true; > else < //Incapable d'ouvrir le fichier d'importation. return false; >> else < //FILE NOT FOUND. return false; >> // runCSVtoArray()

I don’t know what to try. because the number of columns in the Excel file can change. its not a determined amount.. i though i could like set a number of «;» to be found per line. if the line ends before the limit of «;» is reached i could get the next line and stay on the same array key. but there could be 3 columns like there could be 10.. so that wont work. I really don’t know what else.

HMm I just though of this. the title row contains a simple db field name. it should alway’s be on one line 1 word with no spaces. I could use it to determine how many «;» there are.. i think i don’t have a choice I’m, gona try that.

Источник

Читайте также:  Php add property to this
Оцените статью