Jump to content


Photo

Help - Need and Export to CSV script ..


  • Please log in to reply
2 replies to this topic

#1 cheadirl

cheadirl
  • Members
  • Pip
  • Newbie
  • 9 posts

Posted 02 May 2006 - 09:24 AM

Hi,

Im looking for a script that can export MySql data into a CSV / XLS keeping the field headers, I have tried some but keep getting errors (SYLK) can anyone provide me a script ?

Any help would be great

Thanks
Wayne

#2 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 02 May 2006 - 11:35 AM

Please be aware that this forum is not for requesting people to write you scripts - It is for requesting help with scripts that you are writing. But as this is a pretty easy task, here's something that will get you started:
<?php
$data = "";
$result = mysql_query("SHOW COLUMNS FROM `table`") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
    $data .= $row[0].",";
}
$data = substr($data,0,-1)."\r\n";

$result = mysql_query("SELECT * FROM `table`") or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
    foreach($row as $r) {
        $data .= "$r,";
    }
    $data = substr($data,0,-1)."\r\n";
}

$handle = fopen("data.csv","wb")
fwrite($handle,$data)
fclose($handle)

echo "DONE.";
?>
Please note, I have had to leave off the semi-colons after the file functions as there is a bug in the forum that refuses to post a reply with them on.

#3 cheadirl

cheadirl
  • Members
  • Pip
  • Newbie
  • 9 posts

Posted 02 May 2006 - 03:52 PM

Hi,

Thanks for the reply didnt mean to seem like I wanted someone else to write the script I have been trying for ages :)

Unfortuatly the server I use doesn allow FTP access and the fopen etc give access denied this is the code I currently have and its giving the file as an SYLK and failing to open.

Any ideas ?

<?php

include 'login.php';

// DB Connection here

$date = date('d-m-y');
$table_name = "table";

$select = "SELECT * FROM table";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$date $table_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users