【问题标题】:CSV to Json with header row as key以标题行为键的 CSV 到 Json
【发布时间】:2012-05-23 02:52:53
【问题描述】:

我想将 CSV 转换为 Json,使用标题行作为键,每一行作为对象。我该怎么做?

----------------------------------CSV------------ ---------------------

 InvKey,DocNum,CardCode
 11704,1611704,BENV1072
 11703,1611703,BENV1073

---------------------------------PHP------------- ----------------------

  if (($handle = fopen('upload/BEN-new.csv'. '', "r")) !== FALSE) {
       while (($row_array = fgetcsv($handle, 1024, ","))) {
            while ($val != '') {
                foreach ($row_array as $key => $val) {
                        $row_array[] = $val;
                        }
                }
            $complete[] = $row_array;   
            }
            fclose($handle);
        }
        echo json_encode($complete);

【问题讨论】:

    标签: php json


    【解决方案1】:

    只需单独阅读第一行并将其合并到每一行中:

    if (($handle = fopen('upload/BEN-new.csv', 'r')) === false) {
        die('Error opening file');
    }
    
    $headers = fgetcsv($handle, 1024, ',');
    $complete = array();
    
    while ($row = fgetcsv($handle, 1024, ',')) {
        $complete[] = array_combine($headers, $row);
    }
    
    fclose($handle);
    
    echo json_encode($complete);
    

    【讨论】:

    • 你有什么不明白的地方?它打开一个文件句柄,读取第一行$headers,然后读取剩余的行。它将每一行与$headers 组合在一起。见array_combine
    【解决方案2】:

    我发现自己每隔几个月就会将 csv 字符串转换为数组或对象。

    我创建了一个类,因为我很懒,不喜欢复制/粘贴代码。

    该类会将 csv 字符串转换为自定义类对象:

    Convert csv string to arrays or objects in PHP

    【讨论】:

      【解决方案3】:

      对于那些想要详细说明的人 + 一些空间来进一步解析任何行/列而不需要额外的循环:

      function csv_to_json_byheader($filename){
          $json = array();
          if (($handle = fopen($filename, "r")) !== FALSE) {
              $rownum = 0;
              $header = array();
              while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
                  if ($rownum === 0) {
                      for($i=0; $i < count($row); $i++){
      // maybe you want to strip special characters or merge duplicate columns here?
                          $header[$i] = trim($row[$i]);
                      }
                  } else {
                      if (count($row) === count($header)) {
                          $rowJson = array();                     
                          foreach($header as $i=>$head) {
                      // maybe handle special row/cell parsing here, per column header
                              $rowJson[$head] = $row[$i];                     
                          }
                          array_push($json, $rowJson);
                      }
                  }
                  $rownum++;
              }
              fclose($handle);
          }
          return $json;
      }
      

      【讨论】:

        【解决方案4】:
        $feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
        //Read the csv and return as array
        $data = array_map('str_getcsv', file($feed));
        //Get the first raw as the key
        $keys = array_shift($data);  
        //Add label to each value
        $newArray = array_map(function($values) use ($keys){
            return array_combine($keys, $values);
        }, $data);
        // Print it out as JSON
        header('Content-Type: application/json');
        echo json_encode($newArray);
        

        主要要点: https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-02
          • 1970-01-01
          • 1970-01-01
          • 2015-10-06
          • 1970-01-01
          • 1970-01-01
          • 2021-10-09
          相关资源
          最近更新 更多