如何在php语句中引用值?周一大脑冻结
我有一段 php 代码,它从数据库结果集中读取值,将它们推入数组,然后将它们写入 CSV 文件。当每个值进入 CSV 文件时,我需要强制每个值用双引号引起来,但我一辈子都不记得如何做到这一点。
这是写入文件的循环(这实际上包含在另一个循环中以遍历每一行;我显示的这个循环遍历当前选定行中的列):
foreach ($row as $key => $val){
$newrow[$key] = preg_replace("(\r\n|\n|\r|\t)", "", $val);
}
fputcsv($fp, $newrow);
我需要的是将 $val 的值写入文件时用双引号引起来。现在,我得到的结果如下所示:
554,702180,25.00,6FYAK0,9090909090909090
我需要的是:
"554","702180","25.00","6FYAK0","9090909090909090"
有人可以启动我的大脑吗?
I have a piece of php code that reads values from a database resultset, shoves them into an array, and writes them to a CSV file. I need to force each value to be surrounded by double quotes when it goes into the CSV file, and can't for the life of me remember how to do this.
Here's the loop that writes to the file (this is actually contained in another loop to go through each row; this loop I'm showing goes through the columns in the currently-selected row):
foreach ($row as $key => $val){
$newrow[$key] = preg_replace("(\r\n|\n|\r|\t)", "", $val);
}
fputcsv($fp, $newrow);
What I need is for the value of $val to be enclosed in double quotes when it's written to the file. Right now, the results I get look like this:
554,702180,25.00,6FYAK0,9090909090909090
What I need is this:
"554","702180","25.00","6FYAK0","9090909090909090"
Can someone jump start my brain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我将使用
fputscsv
的替代函数:I would use substitute function for
fputscsv
:查看 PHP 站点上的
fputscsv
命令帮助:http ://php.net/manual/en/function.fputcsv.php第四个参数指定封闭字符。这是您要找的吗?不过,据我了解,如果字段需要引号,则 CSV put 只会包含引号,因为字段本身包含分隔符字符或括弧字符。
HAve a look at the
fputscsv
command help on the PHP site: http://php.net/manual/en/function.fputcsv.phpThe fourth parameter specifies an enclosure character. Is this what you are looking for? From what I understand, though, a CSV put will only include the quotes if the field requires it because of either delimeter characters or enclosure characters included in the field itself.
这是一个快速修复方法,但确实有效。
This is a quick fix, but it works.
看起来很简单:
Seems simple enough:
如果您想在不使用
fputscsv
的情况下编写它,那么您可以使用与此类似的函数来生成要写入文件的行:IF you want to write it without using
fputscsv
then you could use a function similar to this to generate a line to write to a file: