Преобразование CSV в JSON с помощью PHP

Я пытаюсь преобразовать CSV-файл в JSON с помощью PHP.

Вот мой код

<?php date_default_timezone_set('UTC'); $today = date("n_j"); // Today is 1/23/2015 -> $today = 1_23 $file_name = $today.'.CSV'; // My file name is 1_23.csv $file_path = 'C:\\Users\\bheng\\Desktop\\qb\\'.$file_name; $file_handle = fopen($file_path, "r"); $result = array(); if ($file_handle !== FALSE) { $column_headers = fgetcsv($file_handle); foreach($column_headers as $header) { $result[$header] = array(); } while (($data = fgetcsv($file_handle)) !== FALSE) { $i = 0; foreach($result as &$column) { $column[] = $data[$i++]; } } fclose($file_handle); } // print_r($result); // I see all data(s) except the header $json = json_encode($result); echo $json; ?> 

print_r($result); // Я вижу все данные (ы)

Затем json_encode($result); и попытался отобразить его, но на экране ничего не отображается. Все, что я вижу, это пустой экран и 0 сообщение об ошибке.

Я что-то делаю неправильно? Кто-нибудь может мне помочь ?

Добавлен результат print_r($result);

 Array ( [Inventory] => Array ( [0] => bs-0468R(20ug) [1] => bs-1338R(1ml) [2] => bs-1557G(no bsa) [3] => bs-3295R(no BSA) [4] => bs-0730R-Cy5" [5] => bs-3889R-PE-Cy7" [6] => 11033R [7] => 1554R-A647 [8] => 4667 [9] => ABIN731018 [10] => Anti-DBNL protein .... more .... 

Попробуйте вот так:

 $file="1_23.csv"; $csv= file_get_contents($file); $array = array_map("str_getcsv", explode("\n", $csv)); $json = json_encode($array); print_r($json); 

Я столкнулся с аналогичной проблемой, и в итоге я использовал ее для рекурсивного преобразования данных в UTF-8 в массив до кодирования в JSON.

 function utf8_converter($array) { array_walk_recursive($array, function(&$item, $key){ if(!mb_detect_encoding($item, 'utf-8', true)){ $item = utf8_encode($item); } }); return $array; } 

От: http://nazcalabs.com/blog/convert-php-array-to-utf8-recursive/

Вы тоже можете попробовать.

  <?php function csvtojson($file,$delimiter) { if (($handle = fopen($file, "r")) === false) { die("can't open the file."); } $csv_headers = fgetcsv($handle, 4000, $delimiter); $csv_json = array(); while ($row = fgetcsv($handle, 4000, $delimiter)) { $csv_json[] = array_combine($csv_headers, $row); } fclose($handle); return json_encode($csv_json); } $jsonresult = csvtojson("./doc.csv", ","); echo $jsonresult; 

Если вы конвертируете динамический CSV-файл, вы можете передать URL-адрес через параметр ( url=http://example.com/some.csv ), и он покажет вам самую последнюю версию:

 <?php // Lets the browser and tools such as Postman know it's JSON header( "Content-Type: application/json" ); // Get CSV source through the 'url' parameter if ( isset( $_GET['url'] ) ) { $csv = explode( "\n", file_get_contents( $_GET['url'] ) ); $index = str_getcsv( array_shift( $csv ) ); $json = array_map( function ( $e ) use ( $index ) { return array_combine( $index, str_getcsv( $e ) ); }, $csv ); } else { $json = "Please set the path to your CSV by using the '?url=' query string."; } // Output JSON echo json_encode( $json ); 

data.csv

Игра, мастерство
Охотник за сокровищами, пилипала
Ракетно-пусковая установка, бибобибо
Ракетный двигатель, hehehohoho

Для преобразования с именем столбца, вот как я это делаю.

csv2json.php

 <?php if (($handle = fopen("data.csv", "r")) !== FALSE) { $csvs = []; while(! feof($handle)) { $csvs[] = fgetcsv($handle); } $datas = []; $column_names = []; foreach ($csvs[0] as $single_csv) { $column_names[] = $single_csv; } foreach ($csvs as $key => $csv) { if ($key === 0) { continue; } foreach ($column_names as $column_key => $column_name) { $datas[$key-1][$column_name] = $csv[$column_key]; } } $json = json_encode($datas); fclose($handle); print_r($json); } 

Выходной результат

 [ { "Game": "Treasure Hunter", "Skill": "pilipala" }, { "Game": "Rocket Launcher", "Skill": "bibobibo" }, { "Game": "Rocket Engine", "Skill": "hehehohoho" } ] 

Альтернативное решение, которое использует аналогичный метод как решение Whirlwind, но возвращает более стандартный результат JSON (с именованными полями для каждого объекта / записи):

 // takes a string of CSV data and returns a JSON representing an array of objects (one object per row) function convert_csv_to_json($csv_data){ $flat_array = array_map("str_getcsv", explode("\n", $csv_data)); // take the first array item to use for the final object's property labels $columns = $flat_array[0]; for ($i=1; $i<count($flat_array)-1; $i++){ foreach ($columns as $column_index => $column){ $obj[$i]->$column = $flat_array[$i][$column_index]; } } $json = json_encode($obj); return $json; // or just return $obj if that's a more useful return value } 

Вы можете проверить, была ли ошибка во время кодирования JSON с помощью json_last_error () . Не могли бы вы сначала попробовать это?