PHP 输出到 CSV
我有以下 PHP 脚本,它从两个 CSV 文件中读取数据,目前我正在将数据放入表中,但我需要将其输出到 CSV 文件...
<?php
$products_file = fopen('Products.csv', 'r');
$manufacturers_file = fopen('Manufacturers.csv', 'r');
$manufacturers = array();
while (($manufacturers_line = fgetcsv($manufacturers_file)) !== FALSE) {
$manufacturers[$manufacturers_line[0]] = $manufacturers_line [1];
}
echo '<table><tr><th>SKU</th><th>Make and Model</th><th>Make and Model</th></tr>';
while (($products_line = fgetcsv($products_file)) !== FALSE ) {
echo '<tr><td>'.$products_line[3].'</td><td>';
echo $manufacturers[$products_line[5]];
echo '</td><td>'.$products_line[4].'</td></tr>';
}
echo '</table>';
fclose($products_file);
fclose($manufacturers_file);
?>
如何使用 fputcsv 来执行此操作?
I have the following PHP script which reads from two CSV files, At the moment I am putting the data into a table however I need it to output to a CSV file...
<?php
$products_file = fopen('Products.csv', 'r');
$manufacturers_file = fopen('Manufacturers.csv', 'r');
$manufacturers = array();
while (($manufacturers_line = fgetcsv($manufacturers_file)) !== FALSE) {
$manufacturers[$manufacturers_line[0]] = $manufacturers_line [1];
}
echo '<table><tr><th>SKU</th><th>Make and Model</th><th>Make and Model</th></tr>';
while (($products_line = fgetcsv($products_file)) !== FALSE ) {
echo '<tr><td>'.$products_line[3].'</td><td>';
echo $manufacturers[$products_line[5]];
echo '</td><td>'.$products_line[4].'</td></tr>';
}
echo '</table>';
fclose($products_file);
fclose($manufacturers_file);
?>
How can I do this using fputcsv ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您只需要更改它呈现 html 表的位置即可将其写入 csv 文件,如 PHP 文档中所示:-
希望有所帮助。
瑞克.
Looks like you just need to change where it renders the html table to write it to a csv file like this as from the PHP documentation:-
Hope that helps.
Rick.
您也可以这样做:
在 while 循环之外声明 $csv:
然后在 while 循环中填充变量:
然后一旦在循环之外,您可以将 $csv 写入文件:
完成!
注意 \n 两边的双引号。如果使用单引号,\n 字符将不会产生预期的结果。
You could also do it this way:
Declare $csv outside your while loop:
Then in your while loop populate the variable:
Then once outside your loop you can write $csv to a file:
Done!
Note the double quote around the \n. If you use single quotes the \n character will not have the expected result.
我建议这样做:
首先,使用
创建一个新数组
数组($products_line[3], $manufacturers[$products_line[5]], $products_line[4]
。然后这个数组被输入到
fputcsv()
。上面的代码同时输出 csv 和 html。如果您不需要 html 输出,请删除
echo
。I'd suggest this:
First, a new array is being created with
array($products_line[3], $manufacturers[$products_line[5]], $products_line[4]
.Then this array is being fed to
fputcsv()
.The above code outputs both csv and html. Remove the
echo
if you don't want html output.