2015-05-13 136 views
0

我們有一個PHP腳本,可以將訂單導出爲.csv文件。我們輸出的系統也要求將每個字段封裝在引號中。用引號括起PHP輸出

這裏是我們設置每個字段的代碼。

$order_data = array(
     'type'    => "H", 
     'order_type'   => 'HOME', 
     'order_date'   => $order->order_date, 
     'account_code'   => "REAL", 
     'document_reference' =>'', 
     'reference1'=>'', 
     'reference2'=>'', 
     'delivery_addess_code'=> '', 
     'billing_first_name' => $order->billing_first_name ." ".$order->billing_last_name, 
     'billing_address_1' => $order->billing_address_1 ." ".$order->billing_address_2, 
     'billing_postcode' => $order->billing_postcode, 
     'delivery_tel_no'=> $order->billing_phone, 
     'delivery_contact'=> $order->billing_first_name, 

該輸出;

H,HOME, 「2015年5月13日13時十九分46秒」,REAL ,,,,, 「奔的公牛」, 「地址1地址2」,

一些被包圍「」而有些不是我們如何讓他們都成爲現實?

+1

有一個功能:http://php.net/manual/en/function.fputcsv.php – CD001

+0

謝謝,雖然使用,輸出三個報價在任何一方「」「」aaa「」「我們只需要一個 – user2377521

+0

在沒有看到實際生成CSV文件的代碼的情況下,這裏沒有任何可用的工具... – CD001

回答

-1

試圖迫使所有類型的字符串,如:

'order_type' => (string) 'HOME'

+0

謝謝,但這不起作用。 – user2377521

0

對於CSV輸出,則需要用雙引號括所有的值。另外,如果值中有雙引號,則需要使用兩個連續的雙引號將這些雙引號轉義。這就是CSV的工作原理。

檢查下面的PHP函數。

function makeCSV($value) { 
    //Encloses each token (Before and after) 
    $CSV_TOKEN_ENCLOSER = '"'; 

    //Used to escape the enclosing character if inside the token 
    $CSV_TOKEN_ENCLOSER_ESCAPER = '""'; 

    //Escape the encloser inside the value 
    $csv_value = str_replace($CSV_TOKEN_ENCLOSER, $CSV_TOKEN_ENCLOSER_ESCAPER, $value); 

    //Enclose the value 
    $csv_value .= $CSV_TOKEN_ENCLOSER . $csv_value . $CSV_TOKEN_ENCLOSER; 

    //Return 
    return $csv_value; 
} 

這樣做的工作,正如我在第一段中所解釋的。你可以在你的情況下,用它作爲這樣的:

$order_data = array(
    'type'  => makeCSV("H"), 
    'order_type' => makeCSV('HOME'), 
    'order_date' => makeCSV($order->order_date), 
    ... 
); 

然而,它看起來就像你有一個會自動封閉引號內您的訂單對象的值,你的代碼。我建議你避免這種情況的代碼,替換與上面介紹的makeCSV功能的使用,最後只用一個標準的PHP破滅通話,讓您的CSV這樣的:

$comma_separated_csv = implode(",", $order_data); 

希望這有助於。

乾杯。