Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I eliminate line break from fgets function in PHP?

I am attempting to make a gallery that calls the image names from a flat file database using the PHP 'fgets' function. There are different sections in the gallery, each with it's own default image, and a small list of images that the users can select from. Everything is working fine, except for one button.

I have one button on the page that is supposed to reset all the galleries to their default images using Javascript OnClick. It works exactly as I want it to, with one small hitch: It copies the line break at the end of the line allong with the characters on the line, breaking the Javascript.

The offending code:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';

//This should output the proper javascript, but does not
<?php
$a = fopen('c.txt','r');
if (!$a) {echo 'ERROR: Unable to open file.'; exit;}
$b = fgets($a);
echo "document.getElementById('i1').src='$b';";
fclose($a);
?>

}

How it outputs:

function back(){
document.getElementById('back').className='back';
document.getElementById('one').className='cellcont';
document.getElementById('i1').src='00.jpg
';}

As you can see, the ending quotation mark and the semi-colon falls on the next line, and this breaks the button.

With the files I'm using now, I can get around this problem by changing, "fgets($a)" to, "fgets($a, 7)" but I need to have it grab the entire line so that if the client decides to enter a file with a longer name, it does not break the gallery on them.

like image 258
Shreger Avatar asked Sep 19 '11 22:09

Shreger


People also ask

Does fgets always add newline?

fgets() won't add a newline; it will include the newline that it read that marks the end of line. That way, you can tell whether you read the whole line or not.

What sequence character does fgets () break on?

What does fgets do? fgets reads in up to (size-1) characters from stream. It stops when it reaches the end of the file (EOF character), a newline ('\n'), or when it has read size-1 characters.

Does fgets read line by line?

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

What does fgets return PHP?

The fgets() function returns a line from an open file.


1 Answers

Use rtrim().

Specifically:

rtrim($var, "\r\n");

(To avoid trimming other characters, pass in just newline.)

like image 116
Ariel Avatar answered Oct 03 '22 22:10

Ariel