PHP 将所有字段用引号引起来 fputcsv()
PHP Wrap ALL fields in quotes fputcsv()
我对 PHP 比较陌生,所以请多多包涵。
我的代码目前看起来像这样:
<?php
require("database.php");
$localfile = "FileName.csv";
$fp = fopen($localfile, "w");
$enclosure = '"';
$delimiter = ',';
if(!$link)
{
echo "DB Connection ERROR";
}
$query = "SELECT * FROM A_Table WHERE Stuff";
$result=mysqli_query($link,$query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp,$row,$delimiter,$enclosure);
}
fclose($localfile);
?>
这按预期工作,但是,客户端要求所有字段都用引号引起来,而不仅仅是那些包含空格的字段。我在网上看到了很多解决方案,但它们似乎都过于复杂,或者似乎建议我在导出 CSV 文件后对其进行编辑。
如果是这样的话,我会坚持下去,但是有没有人有一个相对简单的解决方案来解决我的困境?
例子
正常代码会输出:col1,col2,"col 3",col4
我想输出:"col1","col2","col 3","col4"
如有任何帮助,我们将不胜感激。
提前致谢,
保罗
试试这个来寻找灵感。您可以将 fputcsv()
的 $row
参数替换为您在我的演示中看到的 array_map()
行:
<?php
// Sample values
$unquoted = ['these', 'are', 'some', 'unquoted', 'example', 'values'];
// One-liner to quote every array element and output to new array.
$quoted = array_map(function ($element) { return "\"$element\""; }, $unquoted);
var_dump($quoted);
/*
Output:
array(6) {
[0]=>
string(7) ""these""
[1]=>
string(5) ""are""
[2]=>
string(6) ""some""
[3]=>
string(10) ""unquoted""
[4]=>
string(9) ""example""
[5]=>
string(8) ""values""
}
*/
我对 PHP 比较陌生,所以请多多包涵。
我的代码目前看起来像这样:
<?php
require("database.php");
$localfile = "FileName.csv";
$fp = fopen($localfile, "w");
$enclosure = '"';
$delimiter = ',';
if(!$link)
{
echo "DB Connection ERROR";
}
$query = "SELECT * FROM A_Table WHERE Stuff";
$result=mysqli_query($link,$query);
while($row = mysqli_fetch_assoc($result))
{
fputcsv($fp,$row,$delimiter,$enclosure);
}
fclose($localfile);
?>
这按预期工作,但是,客户端要求所有字段都用引号引起来,而不仅仅是那些包含空格的字段。我在网上看到了很多解决方案,但它们似乎都过于复杂,或者似乎建议我在导出 CSV 文件后对其进行编辑。
如果是这样的话,我会坚持下去,但是有没有人有一个相对简单的解决方案来解决我的困境?
例子
正常代码会输出:col1,col2,"col 3",col4
我想输出:"col1","col2","col 3","col4"
如有任何帮助,我们将不胜感激。
提前致谢, 保罗
试试这个来寻找灵感。您可以将 fputcsv()
的 $row
参数替换为您在我的演示中看到的 array_map()
行:
<?php
// Sample values
$unquoted = ['these', 'are', 'some', 'unquoted', 'example', 'values'];
// One-liner to quote every array element and output to new array.
$quoted = array_map(function ($element) { return "\"$element\""; }, $unquoted);
var_dump($quoted);
/*
Output:
array(6) {
[0]=>
string(7) ""these""
[1]=>
string(5) ""are""
[2]=>
string(6) ""some""
[3]=>
string(10) ""unquoted""
[4]=>
string(9) ""example""
[5]=>
string(8) ""values""
}
*/