2012-02-20 78 views
0

我現在使用此代碼CSV數據導入到我的數據庫額外的空白標題。(感謝弗朗西斯·阿維拉)修剪數據,並刪除

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,,,,,(錯)? 。

回答

3

這個問題可以通過使用RTRIM(字符串$海峽[,字符串$ charlist])來解決:

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

在PHP中您可以使用修邊文:LTRIM(左修整),trim(修剪上雙方),rtrim(右邊修剪)。所有接受參數(字符串$海峽[,字符串$ charlist])$ STR - 輸入字符串$ charlist - string要trimed

$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 

,只要你想你CAND添加許多命令:

$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,','); 
+0

感謝這個好的答案。對不起,但我可以再問一個問題嗎?我怎樣才能修剪和rtrim我的CSV數據呢? – 2012-02-20 18:32:31

+0

再次感謝。但$ xx是我的標題,我需要修剪的部分是以下數據。 – 2012-02-20 19:16:53