What methods can be used to handle and format special characters, such as spaces, retrieved from external sources in PHP scripts for better data manipulation and presentation?

Special characters, such as spaces, retrieved from external sources can be handled and formatted in PHP scripts using functions like trim(), htmlspecialchars(), and utf8_encode(). These functions can help remove extra spaces, encode special characters, and ensure proper UTF-8 encoding for better data manipulation and presentation.

// Example PHP code snippet to handle and format special characters retrieved from external sources

// Retrieve data from external source
$externalData = "   Hello, world!   ";

// Trim extra spaces
$trimmedData = trim($externalData);

// Encode special characters
$encodedData = htmlspecialchars($trimmedData);

// Ensure proper UTF-8 encoding
$utf8EncodedData = utf8_encode($encodedData);

// Output formatted data
echo $utf8EncodedData;