【问题标题】:How do you create and save a csv file from a php while loop to a specific directory? [duplicate]如何从 php while 循环创建 csv 文件并将其保存到特定目录? [复制]
【发布时间】:2021-03-28 17:30:56
【问题描述】:

我正在尝试从中创建一个 csv 文件并将其保存到我目录中的文件中。你将如何做到这一点?谢谢。

$sql = mysql_query("SELECT code, count FROM products WHERE active = '1' ORDER BY code Asc") or die(mysql_error());

while ($row = mysql_fetch_array($sql)) {
    $code = $row['code'];
    $quantity = $row['quantity'];
}

【问题讨论】:

  • 1) 打开一个文件fopen(),在磁盘上你喜欢(或有权限)的任何位置 2) 查找fputcsv() 3) 关闭文件
  • 每次在新代码中使用the mysql_ 数据库扩展this happens 时,它都已被弃用,并且已经存在多年,并且在 PHP7.0+ 中永远消失了。如果您只是学习 PHP,请花精力学习 PDOmysqli 数据库扩展和预处理语句。 Start here
  • 也许像stackoverflow.com/questions/16391528/… 这样的东西可能会有所帮助。

标签: php csv


【解决方案1】:

//打开文件写入

$file = fopen('dir path/filename_to_be_saved.csv', 'w');

 

//保存列标题

fputcsv($file, array('code', 'quantity'));

 

//保存行数据

while ($row = mysql_fetch_array($sql)) { $code = $row['code']; $数量 = $row['数量']; $csv_row = array($code, $quantity);
fputcsv($file, $csv_row);
}

//关闭文件

fclose($file);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多