programing

php에서 CSV 파일을 업로드하고 구문 분석하는 방법

iphone6s 2023. 8. 30. 21:27
반응형

php에서 CSV 파일을 업로드하고 구문 분석하는 방법

저는 php로 csv 파일을 업로드하고 싶습니다.파일이 업로드된 후 CSV 파일의 데이터를 표시하고 싶습니다.저는 이 과제를 수행하는 방법을 예로 들어보고 싶습니다.

이제 훨씬 더 간단한 방법으로 이 작업을 수행할 수 있습니다.

$tmpName = $_FILES['csv']['tmp_name'];
$csvAsArray = array_map('str_getcsv', file($tmpName));

CSV 데이터의 구문 분석된 배열이 반환됩니다.그런 다음 각 문을 사용하여 루프를 반복할 수 있습니다.

테스트되지 않았지만 아이디어를 제공해야 합니다.보기:

<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>

upload.vmdk 컨트롤러:


$csv = array();

// check there are no errors
if($_FILES['csv']['error'] == 0){
    $name = $_FILES['csv']['name'];
    $ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
    $type = $_FILES['csv']['type'];
    $tmpName = $_FILES['csv']['tmp_name'];

    // check the file is a csv
    if($ext === 'csv'){
        if(($handle = fopen($tmpName, 'r')) !== FALSE) {
            // necessary if a large csv file
            set_time_limit(0);

            $row = 0;

            while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                // number of fields in the csv
                $col_count = count($data);

                // get the values from the csv
                $csv[$row]['col1'] = $data[0];
                $csv[$row]['col2'] = $data[1];

                // inc the row
                $row++;
            }
            fclose($handle);
        }
    }
}

php를 사용하여 파일 업로드를 처리하는 방법에 대한 튜토리얼을 쉽게 찾을 수 있고 CSV를 처리하는 기능(수동)이 있지만, 며칠 전에 프로젝트에서 작업했기 때문에 코드를 몇 개 올릴 것입니다.

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

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

   if ( isset($_FILES["file"])) {

            //if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

        }
        else {
                 //Print file details
             echo "Upload: " . $_FILES["file"]["name"] . "<br />";
             echo "Type: " . $_FILES["file"]["type"] . "<br />";
             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

                 //if file already exists
             if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }
             else {
                    //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
        }
     } else {
             echo "No file selected <br />";
     }
}

더 쉬운 방법이 있을 거라는 건 알지만 CSV 파일을 읽고 모든 레코드의 단일 셀을 2차원 배열에 저장합니다.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

    echo "File opened.<br />";

    $firstline = fgets ($file, 4096 );
        //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
    $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

        //save the different fields of the firstline in an array called fields
    $fields = array();
    $fields = explode( ";", $firstline, ($num+1) );

    $line = array();
    $i = 0;

        //CSV: one line is one record and the cells/fields are seperated by ";"
        //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
    while ( $line[$i] = fgets ($file, 4096) ) {

        $dsatz[$i] = array();
        $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

        $i++;
    }

        echo "<table>";
        echo "<tr>";
    for ( $k = 0; $k != ($num+1); $k++ ) {
        echo "<td>" . $fields[$k] . "</td>";
    }
        echo "</tr>";

    foreach ($dsatz as $key => $number) {
                //new table row for every record
        echo "<tr>";
        foreach ($number as $k => $content) {
                        //new table cell for every field of the record
            echo "<td>" . $content . "</td>";
        }
    }

    echo "</table>";
}

그래서 저는 이것이 도움이 되기를 바랍니다. 그것은 단지 코드의 작은 조각일 뿐이고 저는 그것을 테스트하지 않았습니다. 왜냐하면 저는 그것을 약간 다르게 사용했기 때문입니다.댓글이 다 설명이 될 거예요.

@Thomas Clowes 답변의 도움을 받아 아래 스니펫을 만들었습니다.

$tmpName = $_FILES['csv']['tmp_name'];

$csv_data = array_map('str_getcsv', file($tmpName));

array_walk($csv_data , function(&$x) use ($csv_data) {
  $x = array_combine($csv_data[0], $x);
});

/** 
*
* array_shift = remove first value of array 
* in csv file header was the first value
* 
*/
array_shift($csv_data);

// Print Result Data
echo '<pre/>';
print_r($csv_data);    

아래와 같은 결과가 나올 것입니다.

 Array
(
   [0] => Array
    (
        
        [make] => Audi
        [model] => S4
        [grade] => 
        [chassis] => WAUZZZ8K9DA076529
        [year] => 2012
        [kms] => 127000
        [color] => White
        [doors] => 4
        [cc] => 3000
        [engineno] => 
        [trans] => FAT
        [fueltype] => P
        [condition] => 4            
        [price] => 15753
        
    )

)

당신은 PHP 매뉴얼의 파일 업로드 처리 섹션을 원하며, 또한 fgetcsv()를 보고 폭발하는 것이 좋습니다.

나는 느낀다.str_getcsvCSV 문자열을 배열로 구문 분석하는 것이 가장 좋습니다.

  1. 파일을 서버에 업로드해야 합니다.

  2. str_getcsv를 사용하여 파일을 구문 분석합니다.

  3. 배열을 실행하고 웹 사이트의 필요에 따라 정렬합니다.

function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }
public function uploadCsvFile(){
   try{ 
    if($_SERVER['REQUEST_METHOD'] === 'POST'){
        $request = $this->post();
        $fileName = $request->file;
        $file = fopen($fileName, "r"); //open the file
        // $fileName = $_FILES["file"]["tmp_name"];
        while(($column = fgetcsv($file)) !== FALSE){
            $num = count($column);
            $this->dbw->query("insert into csv_upload(first_name,last_name,email,phone,address,pin) values('".$column[0]."','".$column[1]."','".$column[2]."','".$column[3]."','".$column[4]."','".$column[5]."')");
        }

        fclose($file);
    }
    }catch (Exception $e) {
        $this->responseErr($e->getMessage(), 500);
    }
}

사용해 볼 수 있습니다.

function doParseCSVFile($filesArray)
{
    if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

        $strFilePath = $filesArray['frmUpload']['tmp_name']; 

        $strFileHandle = fopen($strFilePath,"r");
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
        $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

        do { 
            if ($line_of_text[0]) { 
                $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                ExecuteQry($strInsertSql);
            }               
        } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

    } else {
        return FALSE;
    }
}

언급URL : https://stackoverflow.com/questions/5593473/how-to-upload-and-parse-a-csv-file-in-php

반응형