Search code examples
phpfgets

In PHP when using fgets() to read from file how to exclude "brake row"


I'm writing simple function witch will read data from myfile.txt with fgets(). Content of file is something like:

1

2

3

4

Function to get first value (1):

$f = fopen ("myfile.txt", "r");
$mystring = fgets ($f);

Now, when I use $mystring to write in file like:

$f1 = fopen ("myfile2.txt", "w"); 
fwrite($f1, 'text' . $mystrin . 'more text');

text 'more text' goes to new row.

I want to have it in in same row with other text.


Solution

  • When reading a file using fgets() it will include the newline at the end. You only need to remove it.

    $mystring = trim ($mystring);
    

    This will remove any leading and trailing whitespaces.