Current Location: Home> Latest Articles> PHP fgetss() Function Explained: How to Use fgetss() to Remove HTML and PHP Tags in Files

PHP fgetss() Function Explained: How to Use fgetss() to Remove HTML and PHP Tags in Files

M66 2025-06-30

PHP fgetss() Function Explained

In PHP, the fgetss() function reads a line from a file pointer and automatically removes HTML and PHP tags from the content. It is commonly used to clean up tags from file contents, ensuring that the output is more pure and readable.

Function Syntax

The basic syntax of the fgetss() function is as follows:

<?php
fgetss(file_pointer, length, tags);
?>

Parameter Explanation

  • file_pointer: This is a valid file pointer that must point to a file opened with fopen().
  • length: The maximum number of bytes to read.
  • tags: Optional. Specifies HTML or PHP tags that should not be removed.

Return Value

The fgetss() function returns the content read from the file, with all HTML and PHP tags stripped. If an error occurs, it returns FALSE.

Example Code

Assume we have a file called new.html with the following content:

<p><strong>Asia</strong> is a <em>continent</em>.</p>

Example 1: Basic Usage

In this example, we use fgetss() to read the file and remove HTML tags:

<?php
$file_pointer = fopen("new.html", "r");

echo fgetss($file_pointer);

fclose($file_pointer);
?>

The output will be:

Asia is a continent.

Example 2: Specifying Length and Keeping Tags

In this example, we pass a length parameter and specify HTML tags to keep:

<?php
$file_pointer = fopen("new.html", "r");

if ($file_pointer) {
    while (!feof($file_pointer)) {
        $buffer = fgetss($file_pointer, 1024, "<p>,<em>");
        echo $buffer;
    }
    fclose($file_pointer);
}
?>

The output will be:

Asia is a <em>continent</em>.

Conclusion

The fgetss() function is a highly useful tool in PHP for handling file contents. It effectively removes HTML and PHP tags, making it ideal for cleaning up content. By using this function properly, you can ensure that the output from files contains only the desired content without unwanted tags.