Traffic monetization

PHP MySQL to CSV script [kichimi.co.uk]
 

PHP MySQL to CSV script

Actually, its for TSV; but it exports all field names and is easily tweaked to output all fields for any requirements.

You can select specific columns in the SQL; and rename them with the 'as' syntax.

You may need to use LIMIT in the SQL for long tables; this could easily be adapted for multiple pages.

$select = "SELECT * FROM tblTable";
$export = mysql_query($select);
$count = mysql_num_fields($export);
 
# use .xls for easy importing into Microsoft Excel :)
$myFile = "myTable.tsv";
$fh = fopen($myFile, 'w');
 
for ($i = 0; $i < $count; $i++) {
	$header .= mysql_field_name($export, $i)."\t";
}
fwrite($fh, $header);
 
while($row = mysql_fetch_row($export)) {
	$data = '';
	foreach($row as $value) {
		if ((!isset($value)) OR ($value == "")) {
			$value = "\t";
		} else {
			$value = str_replace('"', '""', $value);
			$value = '"' . $value . '"' . "\t";
		}
		$line .= $value;
	}
	$data .= trim($line)."\n";
	$data = str_replace("\r", "", $data);
	fwrite($fh, $data);
}
fclose($fh);

To do HTML easily:

$select = "SELECT * FROM tblTable";
$export = mysql_query($select);
$count = mysql_num_fields($export);
 
echo '<style>thead td { font-weight:bold; }</style>';
 
echo '<table><thead><tr>';
for ($i = 0; $i < $count; $i++) {
    echo '<td>'.htmlentities(mysql_field_name($export, $i)).'</td>';
}
echo '</tr></thead><tbody>';
 
while($row = mysql_fetch_row($export)) {
   echo '<tr>';
       foreach($row as $value) {
          echo '<td>'.$value.'</td>';
	}
   echo '</tr>';
}
echo '</tbody></table>';

Thrown together by (Frag)

 
phpmysql2csv.txt · Last modified: 2011/01/24 16:01 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki