繁体   English   中英

使用php将CSV文件转换为mysql数据库

[英]Convert csv file into mysql databse using php

我有一个csv文件,如下所示,我想将其转换为msql数据库。 我的csv文件中有很多行,我想找到一种复制所有内容的快速方法。 有人告诉我知道要查找什么或友善地发布所使用的代码吗? 谢谢! 这是我需要在db中复制的csv文件的示例

Numero SAT,Stato SAT,Tipo servizio,Data attivazione,Imei guasto,Imei consegnato,Marca terminale,Modello terminale,Famiglia guasto,Descrizione guasto
SAT100000002572,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002573,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002574,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002575,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002576,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto

我尝试使用此代码,有人可以修复它吗?

<?php

$message = null;

$allowed_extensions = array('csv');

$upload_path = 'C:\xampp\htdocs\exercise-files\start';

if (!empty($_FILES['file'])) {

    if ($_FILES['file']['error'] == 0) {

        // check extension
        $file = explode(".", $_FILES['file']['name']);
        $extension = array_pop($file);

        if (in_array($extension, $allowed_extensions)) {

            if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) {

                if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) {

                    $keys = array();
                    $out = array();

                    $insert = array();

                    $line = 1;

                    while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {

                        foreach($row as $key => $value) {
                            if ($line === 1) {
                                $keys[$key] = $value;
                            } else {
                                $out[$line][$key] = $value;

                            }
                        }

                        $line++;

                    }

                    fclose($handle);    

                    if (!empty($keys) && !empty($out)) {

                        $db = new PDO('mysql:host=localhost;dbname=satingestione', 'root', '');
                        $db->exec("SET CHARACTER SET utf8");

                        foreach($out as $key => $value) {

                            $sql  = "INSERT INTO `sgestite` (`";
                            $sql .= implode("`, `", $keys);
                            $sql .= "`) VALUES (";
                            $sql .= implode(", ", array_fill(0, count($keys), "?"));
                            $sql .= ")";
                            echo $sql;
                            echo "------------------------------------------------\n";
                            //$statement = $db->prepare($sql);
                            //$statement->execute($value);

                        }

                        $message = '<span class="green">File has been uploaded successfully</span>';

                    }   

                }

            }

        } else {
            $message = '<span class="red">Only .csv file format is allowed</span>';
        }

    } else {
        $message = '<span class="red">There was a problem with your file</span>';
    }

}

?>
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Upload CSV to MySQL</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <link href="/css/core.css" rel="stylesheet" type="text/css" />
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>

<section id="wrapper">  

    <form action="" method="post" enctype="multipart/form-data">

        <table cellpadding="0" cellspacing="0" border="0" class="table">
            <tr>
                <th><label for="file">Select file</label> <?php echo $message; ?></th>
            </tr>
            <tr>
                <td><input type="file" name="file" id="file" size="30" /></td>
            </tr>
            <tr>
                <td><input type="submit" id="btn" class="fl_l" value="Submit" /></td>
            </tr>
        </table>

    </form>

</section>

</body>
</html>

这是一个有效的示例,请相应地更改代码,然后完成:)

<?php 

    //connect to the database
    $connect = mysql_connect("localhost","username","password");
    mysql_select_db("mydatabase",$connect); //select the table
    //

    if ($_FILES[csv][size] > 0) {

        //get the csv file
        $file = $_FILES[csv][tmp_name];
        $handle = fopen($file,"r");

        //loop through the csv file and insert into database
        do {
            if ($data[0]) {
                mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
                    (
                        '".addslashes($data[0])."',
                        '".addslashes($data[1])."',
                        '".addslashes($data[2])."'
                    )
                ");
            }
        } while ($data = fgetcsv($handle,1000,",","'"));
        //

        //redirect
        header('Location: import.php?success=1'); die;

    }

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Import a CSV File with PHP & MySQL</title>
    </head>

    <body>

    <?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> 

我正在解释一种简单的方法。

<?php

    $input = file_get_contents('./path/input.csv');

    //each lines will be an array element
    $lines_array = explode("\n", $input);

    foreach ($lines as $key => $value) {
        //each lines again splitted to objects by comma
        $each_line = explode(",", $value);

        //now you have each object in each line as array
        /* for example 
        $eachline[0] will be equal to 'Numero SAT'
        $eachline[1] will be equal to 'Stato SAT'
        $eachline[2] will be equal to 'Tipo servizio'
        $eachline[3] will be equal to 'Data attivazione'
        and so on  */

        // Now do the process as you wish.

    }

?>

我认为对于MySQL,您可以按规定上传csv文件来创建表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM