What potential issues can arise when sending text with HTML special characters in a PHP API?

When sending text with HTML special characters in a PHP API, the potential issue that can arise is that the special characters may not be properly encoded, leading to security vulnerabilities like cross-site scripting (XSS) attacks. To solve this issue, you should always sanitize and encode user input before sending it in API responses. This can be done using functions like htmlspecialchars() or htmlentities() to encode special characters.

// Sanitize and encode user input before sending in API response
$userInput = '<script>alert("XSS attack")</script>';
$encodedInput = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');

// Send the sanitized input in the API response
echo json_encode(['message' => $encodedInput]);