从数据库下载

时间:2013-09-19 14:33:45

标签: php wordpress

我正在尝试将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);
}

2 个答案:

答案 0 :(得分: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类型列表{ {3}}

答案 1 :(得分:0)

更改

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

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