CSV到Json,标题行为键

时间:2012-05-23 02:52:54

标签: php json

我想将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);

4 个答案:

答案 0 :(得分:14)

分别阅读第一行并将其合并到每一行:

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

答案 1 :(得分:1)

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

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

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

Convert csv string to arrays or objects in PHP

答案 2 :(得分:0)

对于那些喜欢拼写的东西+一些空间来进一步解析任何行/列而没有额外的循环:

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

答案 3 :(得分:0)

$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