How can PHP developers ensure that data with spaces is correctly displayed in form fields?

When displaying data with spaces in form fields, PHP developers can ensure correct formatting by using the htmlspecialchars() function to encode the data before populating the form fields. This function will convert special characters like spaces into their respective HTML entities, preventing any formatting issues or code injection vulnerabilities.

<?php
// Data with spaces
$data = "John Doe";

// Encode data for display in form field
$encoded_data = htmlspecialchars($data, ENT_QUOTES);

// Populate form field with encoded data
echo "<input type='text' name='username' value='$encoded_data'>";
?>