What are the best practices for handling longer strings in PHP when displaying them in XML elements?

When handling longer strings in PHP that need to be displayed in XML elements, it is important to properly escape special characters to ensure the XML remains valid. One common approach is to use the htmlspecialchars function to encode special characters before inserting the string into the XML element. This helps prevent any issues with characters such as ampersands, less than signs, and greater than signs breaking the XML structure.

// Sample long string to be displayed in XML element
$longString = "This is a long string with special characters & < >";

// Escape special characters in the string
$escapedString = htmlspecialchars($longString, ENT_QUOTES, 'UTF-8');

// Create XML element with the escaped string
$xml = "<element>" . $escapedString . "</element>";

// Output the XML
echo $xml;