What is the fgetss() function in PHP?

The fgetss() function in PHP is a built-in function. It gets a line from the file while removing all the tags from a line in an open file. These tags may be HTML or PHP tags.

The method fgetss stops automatically after reaching the specified length, the file reaches its end, or the line ends.

Illustration of how the tags are stripped from a line

Syntax:

fgetss(file, length, tags)

Parameters

file: The filename containing the text and tags being extracted.

length: Number of bytes that the user wants to read using this function. The default value is 1024 bytes.

tags: Optional parameter. Using this parameter, a user can define tags that do not need to be removed.

Return value

The function returns a string without the tags. However, if the function fails for any reason, it returns False.

Key points

  1. Larger files may take a long time to read, as this method reads one line at a time.

  2. For multiple usages of this method, we must clear the buffer.

  3. On failure, this method may return False. However, if the function execution fails, it returns False.

Code

Here is the code for a complete understanding of the fgetss method.

main.php
hello.txt
<?php
// opening the file
$my_file = fopen("hello.txt", "rw");
// removing the tags from first line of the file except the <strong> tag
echo fgetss($my_file, 1024, '<strong>');
// close the file
fclose($my_file);
?>

Explanation

The file hello.txt is opened and appointed with the file stream my_file. The fgetss function is then called to get a maximum of 1024 bytes and such that all tags except the <strong> HTML tags are removed.

The output then shows characters from only the one line of the file with the <p> tag removed.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved