3

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

4 回答 4

19

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

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);
于 2012-05-23T03:04:18.693 回答
1

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

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

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

将csv字符串转换为PHP中的数组或对象

于 2016-04-04T21:33:43.467 回答
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;
}
于 2016-06-23T00:06:34.237 回答
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

于 2019-10-23T06:15:26.590 回答