生成CSV时更改值

时间:2012-03-09 14:07:30

标签: php mysql csv

我正在生成一个包含MYSQL数据库数据的CSV文件。有些字段包含布尔值 - 0和1 我想要的是将布尔值更改为某个字符串和结果文件。

更新:: CSV生成代码

function generateCSV($query, $filename = 'export.csv') {
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";
    $sql_query = $query;

    // Gets the data from the database
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);

    $schema_insert = '';

    for ($i = 0; $i < $fields_cnt; $i++) {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for

    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;

    // Format the data
    while ($row = mysql_fetch_array($result)) {
        $schema_insert = '';
        for ($j = 0; $j < $fields_cnt; $j++) {
            if ($row[$j] == '0' || $row[$j] != '') {

                if ($csv_enclosed == '') {
                    $schema_insert .= $row[$j];
                } else {
                    $schema_insert .= $csv_enclosed .
                            str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                }
            } else {
                $schema_insert .= '';
            }

            if ($j < $fields_cnt - 1) {
                $schema_insert .= $csv_separator;
            }
        } // end for

        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=$filename");
    echo $out;
}

4 个答案:

答案 0 :(得分:2)

对于这些列,请使用CASE语法。

SELECT
    CASE your_column
       WHEN 0 THEN 'zero or any other string'
       WHEN 1 THEN 'one or any other string'
    END AS your_alias
FROM
    your_table_name

答案 1 :(得分:0)

我想你想用文字取代某种状态?那么为什么不直接检查呢?

if ($foo == 0) { echo 'No'; } else { echo 'Yes'; }

答案 2 :(得分:0)

您可以使用CASE语法:

select case when column = 0 then 'somestring_0' when value0 = 1 then 'somestring_1' end from table

http://dev.mysql.com/doc/refman/5.0/en/case-statement.html

答案 3 :(得分:0)

或者您可以使用MySQL IF和REPLACE函数根据您的偏好替换值,作为CASE解决方案的替代方案。