bhylu.com

Advertisements

PHP JSON in HTML

JSON encoding and HTML encoding serve different destinations. Choose a transfer format that keeps data separate from executable source.

How it works

A JSON API response should use an appropriate content type, and browser code should parse it as data. If a server-rendered page deliberately embeds JSON in an HTML script-data context, characters meaningful to HTML need the relevant JSON flags as well. Do not build JavaScript source by concatenating untrusted strings. The local example shows a protective representation rather than executing any received text.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l json-html-context.php
php json-html-context.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · json-html-context.php

<?php
declare(strict_types=1);

$data = ["label"=>"</script><b>Rake</b>"];
$json = json_encode($data,JSON_THROW_ON_ERROR | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);
echo str_contains($json,"<") ? "Raw HTML delimiter present\n" : "HTML delimiters encoded\n";
$decoded = json_decode($json,true,32,JSON_THROW_ON_ERROR);
echo $decoded["label"] === $data["label"] ? "Data round trip preserved\n" : "Changed\n";

Expected result

HTML delimiters encoded
Data round trip preserved

The encoded representation contains no raw less-than delimiter, yet decoding recovers the original data value. This is not permission to insert the decoded value with innerHTML; a browser displaying it as ordinary text should use textContent or a suitable template text context. Keep the handling rule explicit at both ends.

Check the official PHP manual for detailed version and API contracts.