Intereting Posts
Как изменить пароль для отправки сообщения электронной почты в laravel? Создание таблицы SQLite только в том случае, если она еще не существует нужно регулярное выражение для анализа файла csv с двойными кавычками в php Посылка электронной почты Codeigniter не работает Страница обновляется после запроса ajax Symfony2 – PdfBundle не работает Загрузить прогресс с использованием чистого PHP / AJAX? белый IP-адрес списка для доступа администратора Оптимизация производительности веб-приложения визуализации данных Сделать таблицу с несколькими столбцами из файла CSV с помощью PHP Приложение Laravel 5.1 и home.blade.php отсутствуют Раунд до ближайшего кратного пяти в PHP Почему PHP XPath не находит элементы таблицы, хотя Firefox показывает, что они существуют? Почему datetime-> days всегда возвращает положительное число Как отобразить анимацию загрузки, когда файл создан для загрузки?

Чтение файла csv в PHP

Есть несколько способов прочитать CSV-файлы с PHP. Я использовал функцию разрыва, чтобы поместить каждую строку в массив, а затем взорвать запятые и использовать trim, чтобы удалить любые кавычки вокруг данных. Это было грязно …

В PHP 5 теперь есть fgetcsv и * str_getcsv * … Я предполагаю, что это лучший способ сделать это в наши дни, поэтому я взломал код …

$fp = fopen($csv_file['file_path'], 'r'); while (($data = fgetcsv($fp, 0, "\r", '"', "\r")) !== FALSE) { $num = count($data); for ($c=0; $c < $num; $c++) { print_r(str_getcsv($data[$c])); } } 

Кажется, что это работает, но есть ли более безопасный подход? Например, заставляя его работать независимо от того, являются ли разрывы строк \ n или \ r …

Любой вход, который вы можете дать, будет потрясающим!

Solutions Collecting From Web of "Чтение файла csv в PHP"

Это преобразует CSV во вложенный массив. Вам может быть легче:

 <?php /** * */ function csv_entry_to_array(array $row) { $column_count = count($row); $csv_column_values = array(); // Loop through the columns of the current CSV entry and store its value for ($column_index = 0; $column_index < $column_count; $column_index++) { // Store the value of the current CSV entry $csv_column_values[] = $row[$column_index]; } // Return return $csv_column_values; } /** * @param string $input_file_name Filename of input CSV * @param boolean $include_header_in_output Flag indicating whether the first entry in the CSV is included in the output or not. * @param integer $length Must be greater than the longest line (in characters) to be found in the CSV file (allowing for trailing line-end characters). * It became optional in PHP 5. Omitting this parameter (or setting it to 0 in PHP 5.0.4 and later) the maximum line length is * not limited, which is slightly slower. * @param string $delimeter Set the field delimiter (one character only). * @param string $enclosure Set the field enclosure character (one character only). * @param string $escape Set the escape character (one character only). Defaults as a backslash. * $return array Nested indexed array representing the CSV. Empty array on error (eg input file missing, input file not a CSV). */ function csv_file_to_array($input_file_name, $include_header_in_output = TRUE, $length = 1000, $delimeter = ',', $enclosure = '"', $escape = '\\') { // NOTE: this attempts to properly recognize line endings when reading files from Mac; has small performance penalty ini_set('auto_detect_line_endings', TRUE); $csv_array = array(); // Warnings are supressed, but that's OK since the code handles such warnings if (($handle = @fopen($input_file_name, "r")) !== FALSE) { $row_counter = 0; // Iterate over the CSV entries while (($row = fgetcsv($handle, $length, $delimeter, $enclosure, $escape)) !== FALSE) { if ($row_counter === 0 && $include_header_in_output === TRUE) { // This is the first row in the CSV and it should be included in the output $csv_array[] = csv_entry_to_array($row); } else if ($row_counter > 0) { // This is a row in the CSV that needs to be stored in the return array $csv_array[] = csv_entry_to_array($row); } $row_counter++; } // Close file handler fclose($handle); } else { // Input file: some error occured return array(); } return $csv_array; } 

Существует функция для чтения файлов по-разному: file() , которая также работает на обоих типах строк.

И самый короткий метод для чтения во всем CSV-файле:

 $data = array_map("str_getcsv", file($filename)); 

Не уверен, о чем был ваш $num = count() .