0

我正在尝试将 WordPress 数据库中的电子邮件地址列表下载到 .CSV。

任何人都指出我正确的方向:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

$results = $wpdb->get_results( "SELECT * FROM table");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
    $data = json_encode($row);
}

outputCSV($data);

function outputCSV($data) {
    $output = fopen("php://output", "w");
    foreach ($data as $row) {
        fputcsv($output, $row);
    }
    fclose($output);
}
4

2 回答 2

0

改变

while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
    $data = json_encode($row);
}

while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
    $data[] = $row;
}
于 2013-09-19T14:43:03.550 回答
0

这可以解决问题:

header("Content-type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="filename.csv"');
header("Pragma: no-cache");
header("Expires: 0");

echo '"Header 1","Header 2","Header 3"'."\n";

$results = $wpdb->get_results("SELECT * FROM `wp_newsletter_signup`");
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)){
    echo '"' . $row['column1'] . '","' . $row['column2'] . '","' . $row['column3'] . '"' . "\n";
}

die();

请注意我的内容类型,application/vnd.ms-excel由于旧 Windows 机器支持更高,因此我将其用作个人偏好,但您可以继续使用text/csv- 可以在此处找到 mime 类型列表http://fileext.com/file-extension/CSV

于 2013-09-19T14:37:48.793 回答