簡體   English   中英

使用PHP在MySQL中導入.xsl和.csv文件

[英]Import .xsl and .csv file in MySQL using PHP

我在將CSV導入MySQL數據庫時遇到問題:

<div style="border:1px dashed #333333; width:300px; margin:0 auto; padding:10px;">    
<form name="import" method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br />
    <input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection.php");

if(isset($_POST["submit"]))
{
    $file = $_FILES['file']['tmp_name'];
    $handle = fopen($file, "r");
    $c = 0;
    **while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
    {
        $name = $filesop[0];
        $email = $filesop[1];           
        $sql = mysql_query("INSERT INTO selleruser (emailid, pass) VALUES ('$name','$email')");
        $c = $c + 1;
    }**     
        if($sql){
            echo "You database has imported successfully. You have inserted ". $c ." recoreds";
        }else{
            echo "Sorry! There is some problem.";
        }
   }?>

    </div>

我收到此錯誤:

未定義的偏移量:在此行$ email = $ filesop 1處1

如何將.xsl文件導入MySQL數據庫。 在此處輸入圖片說明

似乎您遇到了定界符問題。

fgetcsv($ handle,1000,“,”)

如果使用定界符“;”保存文件,則可以重現此問題。 因此,您可能會發現保存了哪些定界符文件並使用它:

<?php
function detectDelimiter($csvFile)
{
    $delimiters = array(
        ';' => 0,
        ',' => 0,
        "\t" => 0,
        "|" => 0
    );

    $handle = fopen($csvFile, "r");
    $firstLine = fgets($handle);
    fclose($handle); 
    foreach ($delimiters as $delimiter => &$count) {
        $count = count(str_getcsv($firstLine, $delimiter));
    }

    return array_search(max($delimiters), $delimiters);
}
#print_r(detectDelimiter('chart_column.csv'));


$handle = fopen('chart_column.csv', "r");
$delimiter = detectDelimiter('chart_column.csv');
echo "I checked file and found that its delimiter is \"$delimiter\". Will use it further. \n";

$c = 0;
while(($filesop = fgetcsv($handle, 1000, $delimiter)) !== false)
    {
        $name = $filesop[0];
        $email = $filesop[1];           
        echo "emailid = $name , pass = $email\n";
#        $sql = mysql_query("INSERT INTO selleruser (emailid, pass) VALUES ('$name','$email')");
        $c = $c + 1;
    }

結果,我得到了:

~$ cat chart_column.csv 
emailid;pass
asd;asd
fdga;ewrdf
asdf;56gfh
fgh5;fgh
dfg;dfgdf
dfg;dfgdf

~$ php delimiter.php
I checked file and found that its delimiter is ";". Will use it further. 
emailid = emailid , pass = pass
emailid = asd , pass = asd
emailid = fdga , pass = ewrdf
emailid = asdf , pass = 56gfh
emailid = fgh5 , pass = fgh
emailid = dfg , pass = dfgdf
emailid = dfg , pass = dfgdf

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM