Подтвердить что ты не робот

Преобразование 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 .... 
4b9b3361

Ответ 1

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

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

Ответ 2

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

  <?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;

Ответ 3

У меня возникла аналогичная проблема, в результате я использовал это для рекурсивного преобразования данных в 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-recursively/

Ответ 4

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

<?php

// Lets the browser and tools such as Postman know it 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 );

Ответ 5

data.csv

Игра, умение
Охотник за сокровищами, пилипала
Ракетно-пусковая установка, бибобибо
Rocket Engine, 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"
    }
]

Ответ 6

Альтернативное решение, которое использует аналогичный метод как решение @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 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 a more useful return value
}

Ответ 7

Принятый ответ использует file_get_contents() чтобы прочитать весь файл как строку в памяти, а затем explode() чтобы сделать его массивом.

Но это может быть сделано быстрее, меньше в памяти и более полезно:

function ReadCsv($fn)
{
    $lines= file($fn); // read file directly as an array of lines
    array_pop($lines); // you can remove the last empty line (if required)
    $json= json_encode(array_map("str_getcsv", $lines), JSON_NUMERIC_CHECK);
    print_r($json);
}

JSON_NUMERIC_CHECK здесь я использовал JSON_NUMERIC_CHECK чтобы избежать двойных JSON_NUMERIC_CHECK в строках. Это также уменьшает размер вывода и, как правило, помогает JavaScript с другой стороны (например, для вычисления или вывода данных). Остерегайтесь телефонных номеров, хотя!

Ответ 8

Мне понравилось решение @ian-d-miller для преобразования данных в формат ключ/значение, но я продолжал сталкиваться с проблемами с его кодом.

Вот что у меня сработало:

function convert_CSV_to_JSON($csv_data){

    // convert csv data to an array
    $data = array_map("str_getcsv", explode("\n", $csv_data));

    // use the first row as column headers
    $columns = $data[0];

    // create array to hold our converted data
    $json = [];

    // iterate through each row in the data
    foreach ($data as $row_index => $row_data) {

        // skip the first row, since it the headers
        if($row_index === 0) continue;

        // make sure we establish each new row as an array
        $json[$row_index] = [];

        // iterate through each column in the row
        foreach ($row_data as $column_index => $column_value) {

            // get the key for each entry
            $label = $columns[$column_index];

            // add this column value to this row index / column key
            $json[$row_index][$label] = $column_value;       
        }
    }

    // bam
    return $json;
}

Использование:

// as is
$json = convert_CSV_to_JSON($csv);

// encoded
$json = json_encode($json);

Ответ 9

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