PHP - 在自定义Wordpress数据库中上传CSV数据

时间:2015-06-26 05:24:21

标签: php mysql wordpress csv file-upload

my_custom_table:

id              int(11)
product_type    varchar(210)
product_serial  varchar(210)
created_at      datetime


//Upload CSV File
if (isset($_POST['submit'])) {

        if (is_uploaded_file($_FILES['upload_csv']['tmp_name'])) {

                echo "<h1>" . "File ". $_FILES['upload_csv']['name'] ." uploaded successfully." . "</h1>";
        }


        //Import uploaded file to Database
        $handle = fopen($_FILES['upload_csv']['tmp_name'], "r");

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $wpdb->insert("my_custom_table", array(
                    "product_type" => $data[0],
                    "product_serial" => $data[1],
                    "created_at" => current_time('mysql', 1)
                 ));
        }

        fclose($handle);

        print "Import done";
}

使用分隔符$data打印,输出:

Array
(
    [0] => Product Name;product_serial
)

Array
(
    [0] => iPhone 6;iphone-002
)

Array
(
    [0] => iPhone 6;iphone-003
)

使用分隔符$data打印;输出:

Array
(
    [0] => Product Name
    [1] => product_serial
)

Array
(
    [0] => iPhone 6
    [1] => iphone-002
)

Array
(
    [0] => iPhone 6
    [1] => iphone-003
)

使用上面的内容,Product Nameproduct_serial也会插入到应该阻止的DB中。在,执行时,分隔符;也不会输出正确的数组。

如何阻止CSV列名插入并在数据库中插入正确的值?

P.S:使用OpenOffice进行CSV数据插入。格式化是分隔符的问题吗?

1 个答案:

答案 0 :(得分:1)

一般的经验法则是CSV的第一行是列名,因此快速跳过计数器会删除第一行:

$counter = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

    // Skip the first row as is likely column names
    if ($counter === 0) {
        $counter++;
        continue;
    }

    // Insert the row into the database
    $wpdb->insert("my_custom_table", array(
        "product_type" => $data[0],
        "product_serial" => $data[1],
        "created_at" => current_time('mysql', 1)
    ));
}

另一个问题是CSV文件可能有不同的列和行分隔符(AKA有时列由逗号分隔,有时候是半冒号等等)使得解析CSV非常困难。在这个例子中,你的列分隔符似乎是分号,所以修改你的函数参数可能会为你修复它:

while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {

如果您确实必须支持多种类型的分隔符,则以下代码段可以为您提供帮助:

$csvFilePath = $_FILES['upload_csv']['tmp_name'];
$delimiter = $this->detectDelimiter($csvFilePath);

public 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);
}

检测摘录自:HERE

希望这有帮助。