How can PHP distinguish between plain text and HTML content when retrieving data from a database?

When retrieving data from a database, PHP can distinguish between plain text and HTML content by using the htmlspecialchars() function to encode the HTML content. This function will convert special characters in the HTML content to their respective HTML entities, preventing the browser from interpreting them as HTML tags.

// Retrieve data from the database
$data = $row['content'];

// Check if the data contains HTML tags
if (strpos($data, '<') !== false) {
    // Encode HTML content
    $data = htmlspecialchars($data);
}

// Output the data
echo $data;