What is the difference between HTML entities and URL encoding in PHP and when should each be used?

HTML entities are used to encode special characters in HTML code to prevent the browser from interpreting them as part of the markup. URL encoding, on the other hand, is used to encode special characters in a URL to ensure they are properly interpreted by the server. HTML entities should be used when outputting data in HTML, while URL encoding should be used when constructing URLs in PHP.

// Using HTML entities to encode special characters in HTML output
$htmlOutput = "<p>This is a sample & text</p>";
echo htmlentities($htmlOutput);

// Using URL encoding to encode special characters in a URL
$url = "https://www.example.com/?q=" . urlencode("search query");
echo $url;