0

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?

1 Answer 1

2

Use PHP_EOL to add a new line like so:

file_put_contents($file, $instr1 . PHP_EOL, FILE_APPEND | LOCK_EX);   
Sign up to request clarification or add additional context in comments.

1 Comment

You could also concatenate a new line break after your implode if you so desired. I like the verbosity of a dedicated constant like PHP_EOL but sometimes it's a little more reasonable to use \n as in $instr1."\n" especially when you have to place a number of line breaks in a statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.