2010-03-25 76 views
7

我正要詢問相同的問題在這裏aksed問題.... Forcing fputcsv to Use Enclosure For *all* FieldsPHP fputcsv和封閉領域

問題是

當我使用fputcsv寫出來的線 到一個打開的文件句柄,PHP會將 一個封閉字符添加到它認爲需要它的任何列 ,但是 會離開其他列而沒有 機櫃。

例如,你可能最終與 線這樣

11, 「鮑勃」,詹金斯, 「200 MAIN ST。美國 」 等

追加一個虛假的空間的短 每場結束時,是否有任何 辦法迫使fputcsv( 默認爲一個「),以總是括 列與外殼字符?

答案是:

沒有,fputcsv()只圍繞下列條件

/* enclose a field that contains a delimiter, an enclosure character, or a newline */ 
if (FPUTCSV_FLD_CHK(delimiter) || 
    FPUTCSV_FLD_CHK(enclosure) || 
    FPUTCSV_FLD_CHK(escape_char) || 
    FPUTCSV_FLD_CHK('\n') || 
    FPUTCSV_FLD_CHK('\r') || 
    FPUTCSV_FLD_CHK('\t') || 
    FPUTCSV_FLD_CHK(' ') 
) 

沒有 「始終將」 選項下的字段 。

我需要創建一個CSV文件將封閉的每個領域...什麼是最好的解決方案?

在此先感謝...

+0

會改變PHP源是一種選擇?即在你的情況下,是否可以在函數參數中添加一些「永遠包含」標誌? – VolkerK 2010-03-25 11:24:58

回答

7

推出自己的功能 - 它並不難:

function dumbcsv($file_handle, $data_array, $enclosure, $field_sep, $record_sep) 
{ 
    dumbescape(false, $enclosure); 
    $data_array=array_map('dumbescape',$data_array); 
    return fputs($file_handle, 
     $enclosure 
     . implode($enclosure . $field_sep . $enclosure, $data_array) 
     . $enclosure . $record_sep); 
} 
function dumbescape($in, $enclosure=false) 
{ 
    static $enc; 
    if ($enclosure===false) { 
     return str_replace($enc, '\\' . $enc, $in); 
    } 
    $enc=$enclosure; 
} 

(以上是使用UNIX風格的轉義)

C.

+0

$ file_handle,$ data_array,$ enclosure,$ field_sep,$ record_sep - 你能舉例什麼是需要傳遞的值...請...先提前感謝 – Anudeep 2015-07-23 06:01:05

+0

$ file_handle這個變量需要傳遞什麼值@symcbean – Anudeep 2015-07-23 06:07:30

+0

return fputs($ file_handle, $ enclosure 。implode($ enclosure。$ field_sep。$ enclosure,$ data_array) 。$ enclosure。$ record_sep); 我在這一行收到錯誤消息:數組到字符串的轉換 – Anudeep 2015-07-23 06:49:28

1

一種解決方法:假設你的數據是二維數組,你可以添加一個強制引用的字符串,並且你肯定不會包含在你的數據中(這裏是「#@ @#」),然後刪除它:

$fp = fopen($filename, 'w'); 
    foreach ($data as $line => $row) { 
     foreach ($row as $key => $value) { 
      $row[$key] = $value."#@ @#"; 
     }   
     fputcsv($fp, $row); 
    } 

    fclose($fp); 
    $contents = file_get_contents($filename); 
    $contents = str_replace("#@ @#", "", $contents); 
    file_put_contents($filename, $contents);