我正在try 使用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;

?>

print_r($result);//我看到了所有数据

Then I json_encode($result); and tried to display it, but nothing is displaying on the screen at all. All I see is the blank screen, and 0 error message.

Am I doing anything wrong ? Can someone help me ?

增加了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 .... 

推荐答案

Try like this:

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

Json相关问答推荐

Vega-Lite时钟(使用Vega-Lite中的计时器)

如何在使用GO时检测JSON中不需要的字段?

Azure Data Factory JSON输出格式问题

在解码的JSON哈希中搜索数组元素

在MongoDB中检索某个月份和年份的JSON文档

使用JQ将JSON输出转换为CSV复杂 struct

将 REST API - json 输出转换为表 Power BI

使用 jolt 变换压平具有公共列 JSON 的复杂嵌套

无法使用 vue.js 访问 JSON 数组的项目

Nifi - 忽略(或删除)JSON 的第一个数字

通过sql查询读取嵌套Json

使用 Spring 和 JsonTypeInfo 注释将 JSON 反序列化为多态对象模型

如何将 LinkedHashMap 转换为自定义 java 对象?

将json字符反序列化为枚举

数据包含连续问号时无法理解的 jQuery $.ajax() 行为

JSON Schema:验证数字或空值

as_json 没有在关联上调用 as_json

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

如何在 JAVA 中对 JSONArray 进行排序

将 Pandas 数据框转换为嵌套 JSON