Thursday, August 1, 2013

Php CSV Creation

  function escape_csv_value($value) {
                $value = str_replace('"', '""', $value); // First off escape all " and make them ""
                if(preg_match('/,/', $value) or preg_match("/\n/", $value) or preg_match('/"/', $value)) { // Check if I have any commas or new lines
                        return '"'.$value.'"'; // If I have new lines or commas escape them
                } else {
                        return $value; // If no new lines or commas just return the value
                }
  }


 function csv_qstn_bank_yn()
  {

        $db = mysql_connect('localhost', 'root', ''); // Connect to the database
        $link = mysql_select_db('exam_db', $db);        // Select the database name

       $yes_no = 'YesNoQstn';

        $sql = mysql_query("SELECT q_id as Question_id,q_name as Question,ans as answer,s_name as Subject FROM bank_yn"); // Start our query of the database
        $numberFields = mysql_num_fields($sql); // Find out how many fields we are fetching

      

        if($numberFields) { // Check if we need to output anything
                for($i=0; $i<$numberFields; $i++) {
                        $keys[] = mysql_field_name($sql, $i); // Create array of the names for the loop of data below
                        $head[] = $this->escape_csv_value(mysql_field_name($sql, $i)); // Create and escape the headers for each column, this is the field name in the database
                }
                $headers = join(',', $head)."\n"; // Make our first row in the CSV

                $data = '';
                while($info = mysql_fetch_object($sql)) {
                        foreach($keys as $fieldName) { // Loop through the array of headers as we fetch the data
                                $row[] = $this->escape_csv_value($info->$fieldName);
                        } // End loop
                        $data .= join(',', $row)."\n"; // Create a new row of data and append it to the last row
                        $row = ''; // Clear the contents of the $row variable to start a new row
                }
                // Start our output of the CSV
                header("Content-type: application/x-msdownload");
                header("Content-Disposition: attachment; filename=$yes_no.csv");
                header("Pragma: no-cache");
                header("Expires: 0");
                echo $headers.$data;
        } else {
                // Nothing needed to be output. Put an error message here or something.
                echo 'No data available for this CSV.';
        }
    }
 

No comments:

Post a Comment