如何使用 fgetcsv 和 fputcsv 连接两个字符串?
我正在创建一个脚本,该脚本将读取 csv 文件并使用 fgetcsv 将其显示在文本区域上。
$handle = @fopen($filePath, "r"); 如果($句柄) { while (($buffer = fgetcsv($handle, 1000,",")) !== false) { foreach($buffer 为 $buff){ 回显 $buff."\n"; } } }
csv的格式为
“第 1 行-内容 1”、“第 1 行-内容 2”
"line2-content1","line2-content2"使用fgetcsv,内容将显示在文本区域内,不带双引号和逗号。 我可以格式化它,以便它也显示双引号和逗号吗?
然后使用 fputcsv 保存它
$file_to_load = $_GET['文件路径']; $filePath = $dir.$file_to_load; $trans = trim($_POST['txtarea']); $keyarr = split("\n",$trans); $fp = fopen($filePath, 'w'); foreach(数组($keyarr)作为$fields){ fputcsv($fp, $fields); } fclose($fp);
查看csv文件,它保存了csv但显示如下
“第1行-内容1
","第1行-内容2
","第2行-内容1
","line2-content2"它将 "line1-content1" 和 "line1-content2" 分成两行,并在每行末尾添加一个逗号。
- 现在我想保留#2 的格式。我将如何编码?
你可以吗引导我走向正确的方向?谢谢!
I'm creating a script that will read a csv file and display it on a textarea using fgetcsv.
$handle = @fopen($filePath, "r"); if ($handle) { while (($buffer = fgetcsv($handle, 1000,",")) !== false) { foreach($buffer as $buff){ echo $buff."\n"; } } }
The format of the csv is
"line1-content1","line1-content2"
"line2-content1","line2-content2"Using fgetcsv, the content will display inside the textarea without double-quote and comma. Can I format it so that it will also display the duoble quotes and comma?
Then upon saving it using fputcsv
$file_to_load = $_GET['filepath']; $filePath = $dir.$file_to_load; $trans = trim($_POST['txtarea']); $keyarr = split("\n",$trans); $fp = fopen($filePath, 'w'); foreach (array ($keyarr) as $fields) { fputcsv($fp, $fields); } fclose($fp);
Looking on the csv file, it saved the csv but displays it like this
"line1-content1
","line1-content2
","line2-content1
","line2-content2"It separates the "line1-content1" and "line1-content2" into two lines and put a comma after the end of every line.
- Now I want to keep the formatting of #2. How will I code it?
Can you guide me into the right direction? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您想要显示实际的原始 CSV 文本,而不是 CSV 中解析的数据。不使用
fgetcsv()
,只需使用fgets()
,您将获得文本行,无需任何解析,保留引号和逗号。至于 fputcsv,它将写出您传递给它的内容,因此请确保从表单返回的所有内容都已清理(例如,删除多余的换行符)。
Sounds like you want to display the actual raw CSV text, not the parsed data within the CSV. Instead of using
fgetcsv()
, just usefgets()
and you'll get the text line without any parsing, preserving the quotes and commas.As for fputcsv, it's going to write out what you pass into it, so make sure that whatever's coming back from the form is cleaned up (e.g. extra line breaks stripped out).