Sending HTML Code Through JSON

Sending HTML Code Through JSON

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sending HTML Code Through JSON

The short answer is yes, you can absolutely send HTML content through a JSON response from your PHP script. However, treating this task as a simple string substitution often leads to security vulnerabilities or broken rendering on the client side. The core challenge lies in understanding that JSON is a text-based format designed for data interchange, while HTML is a markup language intended for browser rendering. When you embed raw HTML inside a JSON string, the receiving application (whether it's a JavaScript framework like React or a vanilla jQuery app) must explicitly instruct the browser to render that specific portion of the string as HTML rather than displaying it as text.

Escaping and Encoding Nuances

The first pitfall developers encounter is character encoding. If you simply echo a JSON object containing an HTML string without proper handling, characters like quotes (") and backslashes (\) inside your HTML will break the JSON syntax or alter the HTML structure unintentionally. PHP's json_encode() function handles most of this automatically by escaping special characters within strings.

For example, if your PHP script generates:

$html = '<div class="alert">Error: "Connection failed"</div>';
$response = ['content' => $html];
echo json_encode($response);

The output will correctly escape the inner quotes: {"content":"<div class=\"alert\">Error: \"Connection failed\"</div>"}. This is safe for transport. The danger arises on the client side when you try to access this value. If you retrieve the string in JavaScript and assign it directly to an element's innerHTML without verification, you risk Cross-Site Scripting (XSS) if the HTML contains malicious <script> tags injected into $html.

Rendering Strategies on the Client Side

Once the data arrives at your frontend, how you inject it determines whether it renders as code or displays as text. The most common approach is to assign the JSON string directly to an element's innerHTML property. Modern frameworks often handle this automatically when fetching JSON endpoints, but legacy vanilla JS requires manual intervention.

Consider a scenario where you fetch data from your PHP endpoint:

fetch('api/get-report.php')
  .then(response => response.json())
  .then(data => {
    const container = document.getElementById('report-container');
    // This renders the HTML string inside the JSON object
    container.innerHTML = data.content; 
  })
  .catch(error => console.error('Error:', error));

Here, data.content holds the escaped string from PHP. Assigning it to innerHTML tells the browser: "Parse this string as markup." If you were to use textContent instead, the HTML tags would be displayed literally to the user, which is rarely the desired outcome when the specific goal is to send dynamic layouts via JSON.

Security Implications and Validation

Sending HTML via JSON shifts the responsibility of sanitization slightly but does not eliminate it. Even though PHP generates the content, you must trust your own backend logic. If your PHP script pulls data from a database or external API without escaping output for an HTML context before placing it into the JSON string, you are vulnerable to Stored XSS. The JSON format protects the structure of the response, but it does not sanitize the payload.

Always ensure that the $html variable in your PHP script is constructed using safe methods if it involves user input. For instance, if you are building a rich text editor interface where users paste content into a textarea and you want to save that as HTML and return it later:

// Never trust raw input for direct HTML output without sanitization
$userInput = $_POST['content']; 
$response = ['html' => $userInput]; // Dangerous if userInput has <script> tags
echo json_encode($response);

In this case, you must sanitize $userInput before assigning it to the JSON array. While HTML entities are not typically escaped when generating HTML content (unlike escaping for plain text), malicious scripts must be stripped or allowed explicitly based on your security policy.

When to Use This Pattern

This pattern is particularly useful for Single Page Applications (SPAs) that need to dynamically update large sections of the DOM without a full page reload. Instead of returning a raw HTML string from an AJAX call, which can sometimes conflict with framework routing or state management, wrapping it in a JSON structure like {'view': '<template>...</template>'} provides a clear contract between your backend and frontend. It allows you to version your templates as data objects rather than hard-coding them into the HTML template engine itself.

If you are building complex dashboards or reporting tools where layout flexibility is key, sending structured HTML fragments via JSON offers a robust way to decouple the presentation logic from the application logic, provided you maintain strict input validation on the server side.

Our network