Question

I have used a while loop to fetch rows from a database and collect them in an array.

Now what I want to achieve is that on each iteration of this loop, the elements of the array should be written on a new line in a text file

I've tried implode but it's not working. I am probably using it in a completely wrong way. Here is my code:

$query = "SELECT hist FROM loch ;";
$result = mysql_query($query) or die(mysql_error());

$file = "/opt/lampp/htdocs/rrugd/ip.txt";
fopen($file,'a');

$output=array();
while($row=mysql_fetch_row($result))
{

        $instr1 = implode("\n", $row);
        file_put_contents($file, $instr1, FILE_APPEND | LOCK_EX);   
}

I want the output to look like this -

1 2 10 5
1 2 10

But what I am getting is this -

1 2 10 51 2 10

Where am I going wrong?

Was it helpful?

Solution

Use PHP_EOL to add a new line like so:

file_put_contents($file, $instr1 . PHP_EOL, FILE_APPEND | LOCK_EX);   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top