Member Avatar for michelleradu

Hi
I need to save the values printed in a html table from the database in a CSV file if requested by user. I've only managed to save the header of the table so far.
The MySql query is made in a page called reportclient.php which then calls phpReportGen.php in order to nicely diplay the data.
This is phpReportGen.php where I try to save the data in "Report.csv" located on the server:

<?php

class phpReportGenerator
{
	var $mysql_resource;
	var $header;
	var $foolter;
        var $fields = array();
	var $cellpad;
	var $cellspace;
	var $border;
	var $width;
	var $modified_width;
	var $header_color;
	var $header_textcolor;
	var $header_alignment;
	var $body_color;
	var $body_textcolor;
	var $body_alignment;
	var $surrounded;
	
	function generateReport()
	{
		$this->border = (empty($this->border))?"0":$this->border;
		$this->cellpad = (empty($this->cellpad))?"1":$this->cellpad;
		$this->cellspace = (empty($this->cellspace))?"0":$this->cellspace;
		$this->width = (empty($this->width))?"100%":$this->width;
		$this->header_color = (empty($this->header_color))?"#FFFFFF":$this->header_color;
		$this->header_textcolor = (empty($this->header_textcolor))?"#000000":$this->header_textcolor;		
		$this->header_alignment = (empty($this->header_alignment))?"left":$this->header_alignment;
		$this->body_color = (empty($this->body_color))?"#FFFFFF":$this->body_color;
		$this->body_textcolor = (empty($this->body_textcolor))?"#000000":$this->body_textcolor;
		$this->body_alignment = (empty($this->body_alignment))?"left":$this->body_alignment;
		$this->surrounded = (empty($this->surrounded))?false:true;
		$this->modified_width = ($this->surrounded==true)?"100%":$this->width;
		
		//echo "modified_width : ".$this->modified_width."<br>"; 
		
		if (!is_resource($this->mysql_resource))
			die ("User doesn't supply any valid mysql resource after executing query result!");

		/*
		* Lets calculate how many fields are there in supplied resource
		* and store their name in $this->fields[] array
		*/
		
		$field_count = mysql_num_fields($this->mysql_resource);
		$i = 0;
		
		while ($i < $field_count)
		{
			$field = mysql_fetch_field($this->mysql_resource);
			$this->fields[$i] = $field->name;
			$this->fields[$i][0] = strtoupper($this->fields[$i][0]);
			$i++;
		}
		
		
		/*
		* Now start table generation
		* We must draw this table according to number of fields
		*/
		
		echo "<b><i>".$this->header."</i></b>";
		echo "<P></P>";
		
		//Check If our table has to be surrounded by an additional table
		//which increase style of this table
		if ($this->surrounded == true) 
			echo "<table width='$this->width'  border='1' cellspacing='0' cellpadding='0'><tr><td>";
			
		echo "<table width='$this->modified_width'  border='$this->border' cellspacing='$this->cellspace' cellpadding='$this->cellpad'>";
		echo "<tr bgcolor = '$this->header_color'>";
	//	$out="";
		//Header Draw
		for ($i = 0; $i< $field_count; $i++)
		{
			//Now Draw Headers
			echo "<th align = '$this->header_alignment'><font color = '$this->header_textcolor'>&nbsp;".$this->fields[$i]."</font></th>";
			$out .="\" ";
			$out .= $this->fields[$i].'"'.',';
			
		}
        $out .= "\n";
		echo "</tr>";
		
		//Now fill the table with data
		while ($rows = mysql_fetch_row($this->mysql_resource))
		{
			echo "<tr align = '$this->body_alignment' bgcolor = '$this->body_color'>";
			for ($i = 0; $i < $field_count; $i++)
			{
				//Now Draw Data
				echo "<td><font color = '$this->body_textcolor'>&nbsp;".$rows[$i]."</font></td>";
			 	if($i==1)
				  {
				    if (preg_match('/href="([^"]*)"/i', $rows[$i] , $regs))
					   {	$result = $regs[1];} 
					else {	$result = "No URL Found";}
					$out .= "\"".$result.'"'.',';
				  }	
				else  
				  $out .= "\"".$rows[$i].'"'.',';
				//if ($i<>$field_count-1) $out .= ',';

			}
			
			$out .= "\n";
			echo "</tr>";
			
		}
		echo "</table>";
		
		if ($this->surrounded == true) 
			echo "</td></tr></table>";

		echo "csv:". $out;// this prints out correctly
		$f = fopen ('Report.csv','w'); 
        fputs($f, $out);
		fclose($f); 
	    echo "<br /><br />";
		echo"<form action=\"\" method=\"post\" name=\"textform\">";
        echo "<br /><br />";
        echo"<input name=\"download\" type=\"submit\" id=\"download\" value=\"Download\"><br /><br />";
        
	    echo"<a href='report.php' style=\"text-decoration:none\">"."<< Back"."</a\>";
        echo"</form>";
		
	    if ($_POST['download'])
	    { 
		   header("location:download.php");   
  	    }
        	
		
	}
}

?>

And download.php:

<?php
    $output=fopen('Report.csv','r');  
header("Pragma: no-cache"); 
	header('Expires: 0');
    header('Cache-control: private');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.ms-excel');
    header('Content-disposition: attachment; filename="Report.csv"');
	// send output
	readfile('Report.csv');
	
	//print_r($output);
	fclose($output);
?>
Member Avatar for michelleradu

I've also tried saving the table data without column headers and I've sent the $out variable at download.php (so I don't write $out to Report.csv on the server anymore) like this:

while ($rows = mysql_fetch_row($this->mysql_resource))
{
  echo "<tr align = '$this->body_alignment' bgcolor = '$this->body_color'>";
  for ($i = 0; $i < $field_count; $i++)
  {
     echo "<td><font color = '$this->body_textcolor'>&nbsp;".$rows[$i]."</font></td>";
     $out .="\"";
     if($i==1)
      {
         if (preg_match('/href="([^"]*)"/i', $rows[$i] , $regs))
           {	$result = $regs[1];} 
         else 
           {	$result = "No URL Found";}
         $out .= $result."\"".',';
       }	
     else  
          $out .= $rows[$i]."\"".',';
     $out .= ',';

}
			
$out .= "\n";
echo "</tr>";			
}
        echo "<br /><br />";
        echo"<form action=\"\" method=\"post\" name=\"textform\">";
        echo "<br /><br />";
        echo"<input name=\"download\" type=\"submit\" id=\"download\" value=\"Download\"><br /><br />";
        echo"</form>";
		
  if ($_POST['download'])
 { 
    header("location:download.php?string=$out");  
 }

Thats what I have in download.php now:

$out=$_GET['string'];
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename="Report.csv"');
echo $out;

So, now I get an "Unable to read file" error when I try downloading the info. I'm suspecting something is wrong with the content of $out. Any better ideas?

Member Avatar for michelleradu

My CSV file has got this type of contents:

"321","http://www.google.co.uk","link","2010-02-07 22:30:07","0","No","No","0","3","0","70.100.00.04",

I am now convinced this is where the problem is because Excel says it can not read the downloaded CSV file...

Member Avatar for michelleradu

My CSV file has got this type of contents:

"321","http://www.google.co.uk","link","2010-02-07 22:30:07","0","No","No","0","3","0","70.100.00.04",

I am now convinced this is where the problem is because Excel says it can not read the downloaded CSV file...

Problem solved... If anyone bumps into the same issue, look carefully when sending variables from one page to another. It took me a while till I realized I wasnt sending anything to the download.php page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.