How to convert HTML to JSON using PHP?

How to convert HTML to JSON using PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Converting HTML to JSON in PHP: A Practical Guide

You are looking at a specific algorithm implemented in JavaScript that recursively traverses a DOM tree and serializes it into a nested JSON object. The structure it produces maps every element to its tag, populates attributes, and splits content between text nodes (html) and child elements (children). While the logic is sound for client-side processing, porting this exact recursive traversal directly from JavaScript to PHP requires shifting your mental model from manipulating DOM objects to parsing a string into a tree structure.

In PHP, you do not have direct access to the browser's Document object or its native DOM API unless you load the HTML into a DOMDocument instance. The core question is whether you can replicate the toTransform() function. The answer is yes, but you must replace jQuery's .get(0) and attribute iteration with PHP's DOMElement and DOMAttrCollection.

Parsing the String in PHP

The primary difference lies in how you ingest the data. In the JavaScript example, $('#html-output').val() returns a DOM object or an array of nodes because the script runs inside a browser environment where the HTML has already been parsed by the engine.

In PHP, your input is typically a raw string. To replicate the behavior of $(obj).get(0), you must first create a DOMDocument:

$dom = new DOMDocument();
// Suppress warnings for malformed HTML if necessary
libxml_use_internal_errors(true); 
$dom->loadHTML($htmlString, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();

// Get the root element or a specific node
$rootElement = $dom->documentElement;

Once you have the DOMElement object representing your root node (which corresponds to the obj parameter in the JavaScript function), you can traverse it. The logic for extracting attributes remains similar, though PHP's DOMAttrCollection provides an iterator rather than a raw array index.

Implementing the Transformation Logic

The recursive nature of the original script is preserved by calling the transformation function on child nodes. Here is how you would translate the ObjToTransform logic into a PHP method:

function transformNode(DOMElement $node): array {
    $json = [
        'tag' => $node->nodeName,
        'attributes' => []
    ];

    // Iterate through attributes
    foreach ($node->attributes as $attr) {
        $json['attributes'][$attr->name] = $attr->value;
    }

    // Check for children
    $childrenCount = 0;
    foreach ($node->childNodes as $child) {
        if ($child instanceof DOMElement) {
            $childrenCount++;
        }
    }

    if ($childrenCount > 0) {
        $json['children'] = [];
        foreach ($node->childNodes as $child) {
            if ($child instanceof DOMElement) {
                $json['children'][] = transformNode($child);
            } elseif ($child->nodeType === XML_TEXT_NODE && trim($child->textContent) !== '') {
                // Handle text nodes that aren't empty whitespace
                $json['html'] = trim($child->textContent);
            }
        }
    } else {
        // If no child elements, treat remaining text as content
        if ($node->hasChildNodes()) {
             foreach ($node->childNodes as $child) {
                 if ($child->nodeType === XML_TEXT_NODE && trim($child->textContent) !== '') {
                     $json['html'] = trim($child->textContent);
                 }
             }
        }
    }

    // Handle case where there are no children but we want to ensure 'html' key exists if needed
    if (!isset($json['html']) && !isset($json['children'])) {
        $json['html'] = '';
    }

    return $json;
}

Handling the Output Format

The JavaScript code provided includes a FormatJSON function to pretty-print the output. PHP does not have a native requirement to manually format JSON strings with indentation unless you are building a custom API response where specific formatting is desired. For most use cases, you can leverage PHP's built-in json_encode().

If you need the exact indentation style (two spaces) shown in the source image, you can pass the JSON_PRETTY_PRINT flag and optionally use str_replace to adjust whitespace if necessary:

$jsonString = json_encode($resultArray, JSON_PRETTY_PRINT);
echo $jsonString;

Trade-offs and Pitfalls

One significant trade-off when moving from this specific JavaScript implementation to PHP is the handling of mixed content. The original script assumes a simple hierarchy where either an element has children or it holds text (html). In real-world HTML, an element might have child elements and text nodes (e.g., a heading with a span inside). The JavaScript logic provided simplifies this by checking children.length > 0. If true, it only stores attributes and the recursive children array, ignoring immediate text siblings.

In PHP, using DOMElement allows for much more robust parsing of these edge cases. You can explicitly iterate through all child nodes (elements and text) and decide whether to store them in a children array or merge text into an html property based on your specific requirements. This flexibility often makes the PHP approach superior, provided you account for XML namespaces if they are present in your HTML.

If you require a library that handles this complexity out of the box without writing recursive parsers from scratch, consider using packages like html2json. However, understanding the underlying DOM traversal shown above ensures you can debug serialization issues when simple string manipulation fails on complex markup structures.

Our network