使用PHP将CSV转换为JSON

ior*_*ori 24 php csv json

我正在尝试使用PHP将CSV文件转换为JSON.

这是我的代码

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

?>
Run Code Online (Sandbox Code Playgroud)

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 .... 
Run Code Online (Sandbox Code Playgroud)

Whi*_*ind 68

试试这样:

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

  • 对象映射的自定义版本:```php $ dataFolder = realpath(dirname(__ FILE__)); // echo $ dataFolder; $文件= "$ dataFolder/MonwooEcoleDeLaVie_Expressions-Expressions.csv"; $ csv = file_get_contents($ file); $ csvLines = explode("\n",$ csv); $ indexes = str_getcsv(array_shift($ csvLines)); $ array = array_map(function($ e)use($ indexes){return array_combine($ indexes,str_getcsv($ e));},$ csvLines); $ json = json_encode($ array); 的print_r($ JSON); ``` (4认同)
  • array_map 将回调应用于给定数组的元素http://php.net/manual/en/function.array-map.php (2认同)

Kev*_*hew 10

数据.csv

游戏,技能
寻宝猎人,pilipala
火箭发射器,bibobibo
火箭发动机,呵呵呵呵呵呵

要使用列名进行转换,我就是这样做的。

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);
}
Run Code Online (Sandbox Code Playgroud)

输出结果

[
    {
        "Game": "Treasure Hunter",
        "Skill": "pilipala"
    },
    {
        "Game": "Rocket Launcher",
        "Skill": "bibobibo"
    },
    {
        "Game": "Rocket Engine",
        "Skill": "hehehohoho"
    }
]
Run Code Online (Sandbox Code Playgroud)


Ren*_*V R 6

你也可以尝试这种方式.

  <?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;
Run Code Online (Sandbox Code Playgroud)


小智 5

我遇到了类似的问题,我最终使用它在数组上递归地将数据转换为 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;
} 
Run Code Online (Sandbox Code Playgroud)

来自: http: //nazcalabs.com/blog/convert-php-array-to-utf8-recursively/