PHP - 显示两个CSV文件之间的差异

时间:2017-01-12 15:11:11

标签: php

我写了一个小脚本,上传两个csv文件并进行比较。

//设置文件上传目录

 $target_dir1 = "uploads/old/";
 $target_file1 = $target_dir1 . basename($_FILES["fileToUpload1"]["name"]);

 $target_dir2 = "uploads/new/";
 $target_file2 = $target_dir2 . basename($_FILES["fileToUpload2"]["name"]); 

 $uploadOk = 1;

//上传文件

 if ($uploadOk == 0) {
 echo "<BR> Sorry, your files were not uploaded. <BR>";
 } else {
 if (move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"],        $target_file1)) {
    echo "<BR> The 1st file ". basename( $_FILES["fileToUpload1"]["name"]). " has been uploaded. <BR>";
} else {
   echo "<BR> Sorry, there was an error uploading your 1st file. <BR>";
}

if (move_uploaded_file($_FILES["fileToUpload2"]["tmp_name"], $target_file2)) {
    echo "<BR> The 2nd file ". basename( $_FILES["fileToUpload2"]["name"]). " has been uploaded.<BR>";
} else {
   echo "<BR> Sorry, there was an error uploading your 2nd file. <BR>";
}  
} 

//获取第一档文件

$table1 = Array();
 $filehandle1 = fopen($target_file1, "r") ;
 if($filehandle1 !== FALSE) {
while(! feof($filehandle1)) {          // feof end of file
$data1 = fgetcsv($filehandle1, 1000, ",");
array_push($table1, $data1); 
  }
  }
 fclose($filehandle1);  

//获取内容第二个文件

 $table2 = Array();
  $filehandle2 = fopen($target_file2, "r") ;
 if($filehandle2 !== FALSE) {
  while(! feof($filehandle2)) {
  $data2 = fgetcsv($filehandle2, 1000, ",");
 array_push($table2, $data2); 
 }
 }
 fclose($filehandle2);  

//找出这两个文件之间的区别

$headers= array();
$headers =  $table1[0];  

  $i= 0;
  foreach ($table1 as $table) {  
 echo '<BR>';     
 $diff = array_diff($table2[$i], $table);
  if(!empty($diff)) { 
  print_r($diff);
 $chiave= key($diff);
 echo  $headers[$chiave];
 };
 echo '<BR>';
 $i++;
 } 

这是我得到的错误,但两个文件之间的差异是正确显示的:

   Warning: array_diff(): Argument #1 is not an array in /var/www/csv_files/upload.php on line 67 Call Stack: 0.0053 337384 1. {main}() /var/www/csv_files/upload.php:0 0.0064 367220 2. array_diff() /var/www/csv_files/upload.php:67 

2 个答案:

答案 0 :(得分:1)

您收到此错误,因为第一个参数不是需要一个数组的数组。您现在正在检查具有数组的第n个元素但不是整个数组的表。我认为你认为table2是一个二维数组是错误的,而事实并非如此。它使用具有第n个data2元素的一维数组。

希望这有帮助!

答案 1 :(得分:0)

似乎是,有时table2为空或那些CSV文件具有不同的行数 - 这是警告的结果。

所以 - 如果$ table2 [$ i]不为空,你需要添加额外的检查。

我的另一个变体 - 如何更快地读取文件(获取内容第1和第2个文件):

$table1 = file($target_file1);
$table2 = file($target_file2);

然后你可以通过额外的测试做同样的事情:

if (count($table1)) {
  $headers = str_getcsv($table1[0]);

  foreach ($table1 as $key => $table)   {
    if (!isset($table2[$key])) {
        echo 'Row ' . ($key+1) . ' is not exists in second CSV file.';
    } else {
        $diff = array_diff(str_getcsv($table2[$key]), str_getcsv($table));
        // Here is code as in your example
        print_r($diff);
        $chiave = key($diff);
        echo  $headers[$chiave];
    }
  }
}
祝你好运! :)