Jump to content

CSV export problem


wiggst3r

Recommended Posts

Hi

 

I have a script that takes data from a database and outputs the rows into a CSV file.

 

The only problem I have is that it removes the leading '0' from the telephone number if the telephone number in the database is in the format 01234567890 (returns: 1234567890), but if the number

is in the format 01234 567890(returns 01234 567890) it outputs the leading '0'.

 

The field in the database is a varchar(255)

 

This is the code I have to create the CSV

<?php

require_once('functions.php');
$users_result = get_users_result($page = 0);//get all

$fields = mysql_num_fields($users_result);

$csv_output = '';
$data = '';

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

while($row = mysql_fetch_row($users_result))
{
$line = '';
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);

header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=subscribers.xls");
header("Pragma: no-cache");
header("Expires: 0");
print $csv_output."\n".$data;
exit;
?>

 

and the function get_users_result:

 

function get_users_result($page)
{
/*if you pass in a page, it will limit the number of records. Pass in 0 to bypas this and get all records*/
$per_page = PAGINATION_NUMBER_PER_PAGE;
if($page > 1)
{
	$shown_already = $per_page*($page-1);
	$limit_start = $shown_already;
	$limit_sql = " LIMIT $limit_start, $per_page ";
}
elseif(!$page)
{
	$limit_sql = '';
}
else
{
	$limit_sql= " LIMIT 0, $per_page ";
}

$sql="SELECT name, email, organisation, telephone, message, subscribe FROM contacts	 ORDER BY id $limit_sql ";
$result = mysql_query($sql);
return $result;
}

 

Any help appreciated.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/116382-csv-export-problem/
Share on other sites

If you check your database, can you see what you expect - or is the zeros missing?  If they are missing, perhaps you're storing as an integer at the time you write the data, into a text field (hence, the leading zero will be removed).  You could also try changing the field type to Text.

 

Link to comment
https://forums.phpfreaks.com/topic/116382-csv-export-problem/#findComment-598547
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.