使用php从MySQL表创建CSV文件

使用php从MySQL表创建CSV文件

本文介绍了使用php从MySQL表创建CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码创建一个csv文件。但是,我已经避免在字段中打印逗号,因为它被用作一个分隔符(见第22行)。现在我想从字段中删除(回车和换行)。添加$ somecontent。= str_replace(\\\
,,$ val);在线23似乎不工作。任何想法?

this code creates a csv file. However, I have avoided printing out commas in the fields because it is used as a delimeter (see line 22). Now I want to remove (carriage returns and new lines) from the fields. Adding $somecontent .= str_replace("\n", "", $val); on line 23 does not seem to work. any ideas?

@chmod($export_csv, 0777);
    $fe = @fopen($export_csv."/export.csv", "w+");
    if($fe){
        $somecontent = "";
        $fields_count = 0;
        // print field headers
        $db->query($sql_view);
        if($row = $db->fetchAssoc()){
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= ",";
                $somecontent .= ucfirst($key);
            }
        }
        $somecontent .= "\n";

        // print field values
        $db->query($sql_view);
        while($row = $db->fetchAssoc()){
            $fields_count = 0;
            foreach($row as $key => $val){
                if($fields_count++ > 0) $somecontent .= ",";
                $somecontent .= str_replace(",", "", $val);
                $somecontent .= str_replace("\n", "", $val);
            }
            $somecontent .= "\n";
        }

        // write some content to the opened file.
        if (fwrite($fe, $somecontent) == FALSE) echo 'file_writing_error'." (export.csv)";
        fclose($fe);
    }


推荐答案

$ c> $ somecontent。= str_replace(\\\
,,$ val)?我不能在您的代码中找到它。

Where is your $somecontent .= str_replace("\n", "", $val)? I can't find it in your code.

您可以指定一个数组作为 str_replace 的第一个参数。因此,它将用第二个参数替换数组中存在的每个字符串。

You can specify an array as first parameter for str_replace as indicated there. Thus, it would replace each string present in your array with the second parameter.

例如, $ somecontent。= str_replace(array \\ n,\r),,$ val);

这篇关于使用php从MySQL表创建CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-10 22:42