PHP - 导出CSV函数重复每个条目的标题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP - 导出CSV函数重复每个条目的标题相关的知识,希望对你有一定的参考价值。

我们正在创建一个将数据从表导出到CSV的函数。但是,代码似乎重复我们为插入到CSV中的每一行设置的标题,因此最终看起来像这样:

csv data (the red lines are blocked out data but you can see how the headers repeat for each row)

这是我们创建导出的代码:

//inserts data into import table
$sql = "INSERT into import (suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel) values ('$suid', '$studentName', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel')";
if (!$fail) {

    if (mysqli_multi_query($csvDatabase, $sql)) {
            //once imported properly, export csv

        $query = "SELECT suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id DESC LIMIT {$successCount}";  
          $result = mysqli_query($csvDatabase, $query); 
                if ($result->num_rows > 0) {
                  header('Content-Type: text/csv; charset=utf-8');  
                  header('Content-Disposition: attachment; filename=data-export.csv'); 
                    $output = fopen("php://output", "w"); 
                    $headers = array('SUID', 'Student Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
                    fputcsv($output, $headers); 
                     while($row = mysqli_fetch_assoc($result))  
                  {  
                         fputcsv($output, $row);
                  }  
                  fclose($output); 
                    //then delete records in database
                $deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
                    if (mysqli_query($csvDatabase, $deletesql)) {
                        //echo "Record deleted successfully";
                    } else {
                        echo "Error deleting record: " . mysqli_error($csvDatabase);
                    }

        }


    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
    }
 }

关于重复标题的代码中可能发生什么的任何想法?

编辑:包含省略服务器信息的完整代码:

<?php
require_once('connection.php');

$successCount = 0;

if(isset($_POST['submit'])){

$filename = $_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
for($i=0; $i<count($filename); $i++) {
    $file = $filename[$i];
    //open file in read only
    $files = fopen($file, "r");
    //skips first line
    fgets($files); 
    //get data from csv & uses comma to find separate values
        while (($getData = fgetcsv($files, 0, ",")) !== FALSE)
         {
            $fail = FALSE;
            //store SUID from 2nd line in csv
            $suid = $getData[0];
            if (strlen($suid) === 9 && ctype_digit($suid) ) {
            // start ldap look up
            $server="***";
            $basedn="***";

            //Connect to server
            $ds=ldap_connect($server);

            if ($ds) {
                //bind with our special account that retrieves more attributes
                $ldaprdn  = '***';     // ldap rdn or dn
                $ldappass = '***';  // associated password
                $r=ldap_bind($ds,$ldaprdn,$ldappass);    // this is an authenticated bind
                if (substr($suid, 0, 1) === ";" || is_numeric($suid)) {
                        if ($r) {
                            //filter to all objectclasses that the SUID we are looking for
                            $filter = "(&(objectClass=*)(syrEduSUID={$suid}))";

                            //We are only interested in retrieving these attributes
                            $justthese = array("displayName", "syrEduLevel", "syrEduProgramDesc", "syrEduProgram", "mail", "eduPersonPrimaryAffiliation", "eduPersonAffiliation" );

                            // Search SUID
                            $sr=ldap_search($ds, $basedn, $filter, $justthese );
                            //Need to test if the search succeeded. FALSE value means it failed
                            //if ($sr!==FALSE) {
                                //Search found something. Now return Attributes and their values - note, there can be multiple values per attribute. We need to make sure the search only returned one result

                                $entry = ldap_get_entries($ds, $sr);
                                // if we have only one result, return the values, if not, we have a problem

                                if ($entry["count"] == 1) {
                                // get student name and email from suid

                                $studentName = mysqli_real_escape_string($csvDatabase, $entry[0]['displayname'][0]);
                                $studentEmail = mysqli_real_escape_string($csvDatabase, $entry[0]['mail'][0]);
                                $studentAffiliation = mysqli_real_escape_string($csvDatabase, $entry[0]['edupersonprimaryaffiliation'][0]);
                                $studentProgram = mysqli_real_escape_string($csvDatabase, $entry[0]['syreduprogramdesc'][0]);
                                $studentEduLevel = mysqli_real_escape_string($csvDatabase, $entry[0]['syredulevel'][0]);

                                    $successCount++;

                                // close ldap
                                ldap_close($ds);

                                } else {
                                    $msg  = "Ldap search returned 0 or more than one result";
                                    $fail = TRUE;
                                }

                        //} else {
                        //    $msg  = "Search failed";
                        //    $fail = TRUE;
                        //}
                    }
                } else {
                    $msg  = "Bind failed";
                    $fail = TRUE;
                }
            } else {
                $msg  = "LDAP connection failed";
                $fail = TRUE;
            }

                        //inserts data into import table
                        $sql = "INSERT into import (suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel) values ('$suid', '$studentName', '$studentEmail', '$studentAffiliation', '$studentProgram', '$studentEduLevel')";
                        if (!$fail) {

                            if (mysqli_multi_query($csvDatabase, $sql)) {
                                    //once imported properly, export csv

                                $query = "SELECT suid, studentName, studentEmail, studentAffiliation, studentProgram, studentEduLevel from import ORDER BY id DESC LIMIT {$successCount}";  
                                  $result = mysqli_query($csvDatabase, $query); 
                                        if ($result->num_rows > 0) {
                                          header('Content-Type: text/csv; charset=utf-8');  
                                          header('Content-Disposition: attachment; filename=data-export.csv'); 
                                            $output = fopen("php://output", "w"); 
                                            $headers = array('SUID', 'Student Name', 'Student Email', 'Student Affiliation', 'studentProgram', 'Student Edu Level');
                                            fputcsv($output, $headers); 
                                             while($row = mysqli_fetch_assoc($result))  
                                          {  
                                                 fputcsv($output, $row);
                                          }  
                                          fclose($output); 
                                            //then delete records in database
                                        $deletesql = "DELETE FROM import ORDER BY id DESC LIMIT {$successCount}";
                                            if (mysqli_query($csvDatabase, $deletesql)) {
                                                //echo "Record deleted successfully";
                                            } else {
                                                echo "Error deleting record: " . mysqli_error($csvDatabase);
                                            }

                                }


                            } else {
                                echo "Error: " . $sql . "<br>" . mysqli_error($csvDatabase);
                            }
                         }
                }
        }

    //closes file    
    fclose($files); 
     }
} else {
    echo "You did not upload a CSV file or the CSV file is blank.";
}
} else {
?>
答案

正如IdontDownVote所指出的,代码被放置在每个文件循环中。一旦取出并放在fclose($ files)之后,它就不会重复标题。

以上是关于PHP - 导出CSV函数重复每个条目的标题的主要内容,如果未能解决你的问题,请参考以下文章

php 示例导出脚本,用于将MODX资源转换为CSV条目,以便在另一个站点中导入。

努力从 QTableWidget 导出 csv 数据 [重复]

使用 csv_from_result 在 CSV 导出中返回字符串而不是数据库条目

如何编写python程序将csv数据文件导入关系数据库而不插入重复条目

通过 PHP 导出为 CSV

如何使用 php 以 .dat 或 .txt 格式导出文件