What are best practices for handling whitespace or special characters when reading data from a text file in PHP?

When reading data from a text file in PHP, it's important to handle whitespace and special characters properly to avoid unexpected behavior or errors. One way to do this is by using functions like trim() to remove leading and trailing whitespace, and htmlspecialchars() to convert special characters to HTML entities. Additionally, using regular expressions can help to filter out unwanted characters or format the data as needed.

// Open the text file for reading
$file = fopen('data.txt', 'r');

// Read each line from the file
while (!feof($file)) {
    $line = fgets($file);
    
    // Trim leading and trailing whitespace
    $trimmedLine = trim($line);
    
    // Convert special characters to HTML entities
    $cleanedLine = htmlspecialchars($trimmedLine, ENT_QUOTES);
    
    // Process the cleaned data as needed
    echo $cleanedLine . '<br>';
}

// Close the file
fclose($file);