簡體   English   中英

從CSV文件讀取行並導出到JSON

[英]Read row from CSV file and export to JSON

我想將CSV文件導出為JSON文件,要求在“推薦”字段中讀取值並寫入JSON文件。 范例:在第1行中,recomnend = 2將讀取id = 2的行,並打印到值為:id,product_id,title的JSON文件中。

$json = array();

        $json['id'] = $row['id'];
        $json['product_id'] = $row['product_id'];
        $json['title'] = $row['title'];
        $json['outline'] = $row['outline'];
        $recom[] = $json;  
print json_encode($recom);

http://ns0.upanh.com/b6.s33.d3/3a3ebb93a87c5703f673b399d5613ec2_50639320.untitled.png

我不知道執行此操作的其他方法,但是以下方法會起作用。 使用此方法意味着您必須使用列索引,而不是其名稱。 如果您知道所需值的列索引,那么這應該不是問題,但我只是想提一提:

$fp = fopen('test.csv','r') or die("**! can't open file\n\n");
while($csv_line = fgetcsv($fp,1024)) {
    $id = $csv_line[0];
    $product_id = $csv_line[1];
    $title = $csv_line[2];
    $outline = $csv_line[3];        
}
fclose($fp) or die("**! can't close file\n\n");

現在,因為您將有多行,所以我建議以下內容將它們保存到一個JSON對象中:

$fp = fopen('test.csv','r') or die("**! can't open file\n\n");
$i = 0;
while($csv_line = fgetcsv($fp,1024)) {
    $i++;
    $json['json_'.$i]['id'] = $csv_line[0];
    $json['json_'.$i]['product_id'] = $csv_line[1];
    $json['json_'.$i]['title'] = $csv_line[2];
    $json['json_'.$i]['outline'] = $csv_line[3];        
}
$json['total_lines'] = $i;
print json_encode($json);
fclose($fp) or die("**! can't close file\n\n");

使用這種方法,您可以將每一行保存為一個子JSON對象,從而可以提取總數並解析對象以提取行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM