我正在尝试使用PHP处理现有的.csv文件!我查看了大多数StackOverflow问题,发现the answer from user "Myke Black"最适合我的需求。
我设置了$id=2
,因此我希望代码会影响我的.csv文件的第2行,并且将生成一个新的生成的没有第2行的.csv文件。
这是我的代码:
$id=2;
$fptemp = fopen('files/FL_insurance_small-temp.csv', "a+");
if (($handle = fopen('files/FL_insurance_small.csv', "r")) !== FALSE) {
while (($id= fgetcsv($handle)) !== FALSE) {
if ($id != $data[0]) {
$list = array($data);
fputcsv($fptemp, $list);
}
}
fclose($handle);
fclose($fptemp);
rename('files/FL_insurance_small-temp.csv','files/output/FL_insurance_small_new.csv');
echo "Row with ID: ".$id." successfully deleted!";
} else {
print "There seems to be a problem.";
}
一切似乎都能正常工作,因为会在输出文件夹中生成一个新文件。我的问题是,新生成的文件为空。有谁知道为什么?我想念什么?
示例数据(.csv):
policyID,statecode,county,eq_site_limit,hu_site_limit,fl_site_limit,fr_site_limit,tiv_2011,tiv_2012,eq_site_deductible,hu_site_deductible,fl_site_deductible,fr_site_deductible,point_latitude,point_longitude,line,construction,point_granularity
119736,FL,"CLAY COUNTY",498960,498960,498960,498960,498960,792148.9,0,9979.2,0,0,30.102261,-81.711777,Residential,Masonry,1
448094,FL,"CLAY COUNTY",1322376.3,1322376.3,1322376.3,1322376.3,1322376.3,1438163.57,0,0,0,0,30.063936,-81.707664,Residential,Masonry,3
206893,FL,"CLAY COUNTY",190724.4,190724.4,190724.4,190724.4,190724.4,192476.78,0,0,0,0,30.089579,-81.700455,Residential,Wood,1
333743,FL,"CLAY COUNTY",0,79520.76,0,0,79520.76,86854.48,0,0,0,0,30.063236,-81.707703,Residential,Wood,3
172534,FL,"CLAY COUNTY",0,254281.5,0,254281.5,254281.5,246144.49,0,0,0,0,30.060614,-81.702675,Residential,Wood,1
785275,FL,"CLAY COUNTY",0,515035.62,0,0,515035.62,884419.17,0,0,0,0,30.063236,-81.707703,Residential,Masonry,3
995932,FL,"CLAY COUNTY",0,19260000,0,0,19260000,20610000,0,0,0,0,30.102226,-81.713882,Commercial,"Reinforced Concrete",1
223488,FL,"CLAY COUNTY",328500,328500,328500,328500,328500,348374.25,0,16425,0,0,30.102217,-81.707146,Residential,Wood,1
433512,FL,"CLAY COUNTY",315000,315000,315000,315000,315000,265821.57,0,15750,0,0,30.118774,-81.704613,Residential,Wood,1
142071,FL,"CLAY COUNTY",705600,705600,705600,705600,705600,1010842.56,14112,35280,0,0,30.100628,-81.703751,Residential,Masonry,1
253816,FL,"CLAY COUNTY",831498.3,831498.3,831498.3,831498.3,831498.3,1117791.48,0,0,0,0,30.10216,-81.719444,Residential,Masonry,1
894922,FL,"CLAY COUNTY",0,24059.09,0,0,24059.09,33952.19,0,0,0,0,30.095957,-81.695099,Residential,Wood,1
422834,FL,"CLAY COUNTY",0,48115.94,0,0,48115.94,66755.39,0,0,0,0,30.100073,-81.739822,Residential,Wood,1
582721,FL,"CLAY COUNTY",0,28869.12,0,0,28869.12,42826.99,0,0,0,0,30.09248,-81.725167,Residential,Wood,1
答案 0 :(得分:2)
读取文件时-您要覆盖的$id
行。相反,您的循环应将值分配给$data
……
$rowcount = 1;
while ($data= fgetcsv($handle)) {
if ($id != $rowcount++) {
fputcsv($fptemp, $data);
}
}
$rowCount
是当前正在读取的行,因此在读取新行时将其与每一行进行比较。
这还将删除对$list
的冗余分配。
要“删除”(或省略)记录列表...
$id= [2,5,7];
$rowcount = 1;
while ($data= fgetcsv($handle)) {
if (!in_array($rowcount++, $id)) { // Only write row if not in the list
fputcsv($fptemp, $data);
}
}