Jump to content

Magical line breaks appearing?


Recommended Posts

Hey I am trying to write to a csv file with the data in my database.  My problem I am having is that when I echo out to the browser everything is fine, but when I try writing to the file I get a lot of line breaks and that throws everything off for the csv file.

 

Here's my code:

$query = "SELECT * FROM $table";
$result = mysql_query($query);
$numcolumns = mysql_num_fields($result);
$numrows = mysql_num_rows($result);

$file = "testFile.csv";
$fh = fopen($file, 'w') or die("can't open file");

while($row = mysql_fetch_array($result))
{

for($i = 0; $i <= ($numcolumns - 1); $i++)
{
	if($i < ($numcolumns - 1))
	{
		$string = $row[$i] . ",";
		echo $string;
		fwrite($fh, $string);
	}
	else
	{
		$string = $row[$i];
		echo $string;
		fwrite($fh, $string);
	}
}
$string = "\n";
echo "<br />";
fwrite($fh, $string);
}

fclose($fh);

 

My output to the browser looks like this for one record.. which is how it should look:

(Had to edit the content a bit for confidential reasons)

######,12/31/99 ,123 Drive,City,TX ,##### ,County 

 

And here is what I get in the csv file when I open it up on notepad:

######,12/31/99
,123 Drive
,City
,TX
,#####
,County

 

Any idea where these line breaks are coming from?  Is it because the data is being pulled from a database?  Any help on how to fix this would be great!! Thanks.

Link to comment
https://forums.phpfreaks.com/topic/238216-magical-line-breaks-appearing/
Share on other sites

I realize you've marked this as "solved", but there is a much easier way of generating the string to be written. Use a temporary array and the implode function which would transform your code

<?php

while($row = mysql_fetch_array($result))
{

for($i = 0; $i <= ($numcolumns - 1); $i++)
{
	if($i < ($numcolumns - 1))
	{
		$string = $row[$i] . ",";
		echo $string;
		fwrite($fh, $string);
	}
	else
	{
		$string = $row[$i];
		echo $string;
		fwrite($fh, $string);
	}
}
$string = "\n";
echo "<br />";
fwrite($fh, $string);
}
?>

into

<?php
while($row = mysql_fetch_array($result))
{
$tmp = array();
for($i = 0; $i <= ($numcolumns - 1); $i++)
{
	$tmp[] = $row[$i];
}
echo implode(',',$tmp) . "<br />\n";
fwrite($fh, implode(',',$tmp). "\n");
}
?>

Much simpler and less error prone.

 

Ken

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.