How can HTML entities like "&" be correctly implemented in PHP when creating XML files?

When creating XML files in PHP, special characters like "&" need to be encoded as HTML entities like "&" to ensure the XML is valid and can be parsed correctly. This can be done using the htmlspecialchars() function in PHP to convert special characters to their respective HTML entities.

$data = "This is an example with & special characters";
$encoded_data = htmlspecialchars($data, ENT_XML1);
$xml = "<root><data>{$encoded_data}</data></root>";

file_put_contents('example.xml', $xml);