Anu*_*eep 10 php csv codeigniter
我需要使用PHP将所有字符串和数字用双引号放在CSV文件中.
如何在双引号内的所有数据中从PHP创建CSV文件?
我正在使用此代码生成CSV - 我正在使用codeigniter框架
$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');
Run Code Online (Sandbox Code Playgroud)
输出我得到:
"XXX XX XX",3,68878353,,xxxx@xxxx.xxx.xx
Run Code Online (Sandbox Code Playgroud)
预期产出:
"XXX XX XX","3","68878353","","xxxx@xxxx.xxx.xx"
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
先感谢您
在PHP中构建CSV时,您应该使用PHP 5提供的fputcsv函数
从文档中,有以下参数:
int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
Run Code Online (Sandbox Code Playgroud)
你有:
由于,分隔符和"机箱的默认值,您不需要添加更多内容.这将正确覆盖字符串.这些数字是另一回事.这个SO问题有一个解决方法,我在输入大部分内容之后找到了这个问题,然后仍然遇到数字问题:
对这个解决方案不满意,但这是我所做的和工作的.我们的想法是在fputcsv上设置一个空字符作为外壳字符,并在数组的每个元素上添加一些引号.
Run Code Online (Sandbox Code Playgroud)function encodeFunc($value) { return "\"$value\""; } fputcsv($handler, array_map(encodeFunc, $array), ',', chr(0));
Anu*_*eep -1
我有解决方案这个函数将多维数组转换为带双引号的 CSV 和
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.'";');
}
Run Code Online (Sandbox Code Playgroud)