修剪csv文件中的数据并删除多余的空白标题

时间:2012-02-20 18:07:56

标签: php csv upload

我现在正在使用此代码将csv数据导入我的数据库。(感谢Francis Avila)

 if (($handle = fopen($source_file, "r")) !== FALSE) {
     $columns = fgetcsv($handle, $max_line_length, ",");
     $esc_columns = array();
     foreach ($columns as &$column) {
         $column1 = str_replace(".","",$column);
         $column = preg_replace("/\s*,\s*/",",",$column1);
         $esc_columns[] = escapeSqlName($column);
     }

     $esc_columns[] = escapeSqlName('custgroup');
     $esc_columns[] = escapeSqlName('user_id');
     $esc_columns[] = escapeSqlName('mylabel');

     $x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
     $xx = str_replace(' ', '', $x);

     $sqlsmttempl = 'INSERT DELAYED INTO %s (%s) VALUES (%s)';
     $sqlsmt = sprintf($sqlsmttempl,
         escapeSqlName($target_table), 
         $xx, 
         implode(',',array_fill(0, count($esc_columns), '?')) 
);


     $db = new PDO("mysql:host=localhost;dbname=Data;","root",""); 

     $insert = $db->prepare($sqlsmt); 

     while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
    while(count($data) < count($columns)) {
        $data[] = NULL;
    }

    $data[] = $_POST['custgroup'];
    $data[] = $_POST['user_id'];
    $data[] = $_POST['mylabel'];

    $insert->execute($data); 
}

之前我在标题空白区遇到了一些问题,所以我添加了

     $x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
     $xx = str_replace(' ', '', $x);

所以现在空格将被忽略。

但是数据中的空格怎么样?(只是在逗号的前面和后面)。我试过trim($data),但我知道这是错误的。

当标题包含其他额外逗号时,我不知道如何处理上传,例如:

Name,Address,Phone,,,,,(错误)而非Name,Address,Phone(正确)

有什么建议吗?先谢谢。

1 个答案:

答案 0 :(得分:3)

使用rtrim(string $ str [,string $ charlist])可以解决问题:

$x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
$xx = str_replace(' ', '', $x);
$xx = rtrim($xx,',');

对于在php中修剪文本,您可以使用:ltrim(左侧修剪),修剪(两侧修剪),rtrim(右侧修剪)。所有接受参数(字符串$ str [,string $ charlist])$ str - 输入字符串$ charlist - 要训练的字符串

$xx = trim($xx); //exclude spaces both sides so for "  text  " => "text"
$xx = ltrim($xx); //exclude spaces left side so for "  text  " => "text  "
$xx = rtrim($xx); //exclude spaces right side so for "  text  " => "  text"

$xx = rtrim($xx,','); //adding second parameter ',' will not trim spaces, will trim coma

您可以根据需要添加许多命令:

$x = preg_replace("/\s*,\s*/", ",", implode(',',$esc_columns));
$xx = str_replace(' ', '', $x);

$xx = trim($xx); //trim spaces from both sides
$xx = trim($xx,','); //trim comas from both sides

注意:

$xx = trim($xx,','); //this is faster (only one function call)

//equivalent with
$xx = ltrim($xx,',');
$xx = rtrim($xx,',');