使用PHP将CSV文件中的每个字段都包含双引号吗?
问题描述:
我需要使用PHP在CSV文件中添加所有带双引号的字符串和数字.
I need to put all strings and number with double quotes in CSV file using PHP.
如何从PHP中用双引号引起的所有数据创建CSV文件?
How can I create CSV file from PHP in all data within double quotes ?
我正在使用此代码生成CSV-我正在使用codeigniter框架
I am using this code to generate CSV - I am using codeigniter framework
$array = array(
array(
(string)'XXX XX XX',
(string)'3',
(string)'68878353',
(string)'',
(string)'xxxx@xxxx.xxx.xx',
),
);
$this->load->helper('csv');
array_to_csv($array, 'blueform.csv');
我得到的输出:
"XXX XX XX",3,68878353,,xxxx@xxxx.xxx.xx
预期输出:
"XXX XX XX","3","68878353","","xxxx@xxxx.xxx.xx"
array_to_csv的代码
if (!function_exists('array_to_csv')) {
function array_to_csv($array, $download = "") {
if ($download != "") {
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $download . '"');
}
ob_start();
$f = fopen('php://output', 'w') or show_error("Can't open php://output");
$n = 0;
foreach ($array as $line) {
$n++;
if (!fputcsv($f, $line)) {
show_error("Can't write line $n: $line");
}
}
fclose($f) or show_error("Can't close php://output");
$str = ob_get_contents();
ob_end_clean();
if ($download == "") {
return $str;
} else {
echo $str;
}
}
}
提前谢谢
答
我有解决方案 此函数将带有双引号和
I have got solution this function convert multi dimension array into CSV with double quote and
function arr_to_csv($arr)
{
$filePointer="export.csv";
$delimiter=",";
$enclosure='"';
$dataArray =$arr;
$string = "";
// No leading delimiter
$writeDelimiter = FALSE;
//foreach($dataArray as $dataElement)
foreach ($dataArray as $key1 => $value){
foreach ($value as $key => $dataElement)
{
// Replaces a double quote with two double quotes
$dataElement=str_replace("\"", "\"\"", $dataElement);
// Adds a delimiter before each field (except the first)
// Encloses each field with $enclosure and adds it to the string
if($writeDelimiter) $string .= $delimiter;
// $new_string = $enclosure . $dataElement . $enclosure;
$string .= $enclosure . $dataElement . $enclosure;
// Delimiters are used every time except the first.
$writeDelimiter = TRUE;
} // end foreach($dataArray as $dataElement)
$string .= "\n";
}
// Append new line
$string .= "\n";
//$string = "An infinite number of monkeys";
print($newstring);
// Write the string to the file
// fwrite($filePointer,$string);
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filePointer.'";');
}