首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将php版本4中的mysql查询导出到csv

将php版本4中的mysql查询导出到csv
EN

Stack Overflow用户
提问于 2016-10-20 14:11:31
回答 2查看 138关注 0票数 0

编辑我的原始帖子。我找到答案了!在帮助下:)

现在,通过使用下面的代码来完成此工作,并感谢注释中对此提供的建议:

代码语言:javascript
复制
<?php

$f = fopen('incident_csv\test.csv', 'w');

$query = "
select column1, column2, column3
from table
where columns = values
";

$var1 = mysql_query($query, $database connection variable);

/* From Monkey Zeus */

$csv_lines = array();

// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){

$columns = array();

// Loop each column for the row
foreach($row as $k=>$v){
// Surround column item in double-quotes and escape double-quotes with double-double-quotes
$columns[] = '"'.str_replace('"', '""', $v).'"';
}

// Join on a comma
$csv_lines[] = implode(',', $columns);
}

// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);

/* From Monkey Zeus */  

fwrite($f, $csv_file_string);

?>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-20 14:33:58

你可以这样做:

代码语言:javascript
复制
$csv_lines = array();

// Loop your records from the DB
while ($row = mysql_fetch_assoc($var1)){

    $columns = array();

    // Loop each column for the row
    foreach($row as $k=>$v){
        // Surround column item in double-quotes and escape double-quotes with double-double-quotes
        $columns[] = '"'.str_replace('"', '""', $v).'"';
    }

    // Join on a comma
    $csv_lines[] = implode(',', $columns);

    // Write to the file right away. You are using PHP4 so I imagine system memory is not plentiful
    // If you use this then there is no need for the "$csv_lines[] =" from above
    // nor the $csv_file_string after the while loop
    // fwrite($f, implode(',', $columns)."\n");
}

// fclose($f); // If you choose to write to the file during the while loop then close the file handle when you are finished

// Create full CSV file by joining on a newline
$csv_file_string = implode("\n", $csv_lines);
票数 0
EN

Stack Overflow用户

发布于 2016-10-20 14:17:05

您可以简单地使用arrayToCsv函数:

代码语言:javascript
复制
function arrayToCsv($array) {
    $string = array();

    foreach ($array as $field) {
        $string[] = implode(';', $field);
    }

    return implode("\n", $string);
}

$a = array(
    array('First Field of First Line', 'Second Field of First Line'),
    array('First Field of Second Line', 'Second Field of Second Line')
);
fwrite($f, arrayToCsv($a));

但是,请记住将您的$f设置为$f = fopen('file location', 'w');

希望我能帮上忙。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40156896

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档