How to saveHTML of DOMDocument without HTML wrapper?

How to saveHTML of DOMDocument without HTML wrapper?

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

Stefan Bogdanescu

Founder & Senior Architect

Saving DOMDocument Content Without Wrappers

When working with PHP's DOMDocument, a common frustration arises when trying to extract specific content without triggering automatic formatting wrappers like <html>, <body>, or even nested <p> tags. The standard approach often involves calling $d->saveXML() on a specific node, but this method has distinct limitations depending on the structure of your input HTML.

If you attempt to retrieve a simple paragraph using $d->getElementsByTagName('p')->item(0), the output is clean and contains only that element's inner text and tags. However, as soon as your content includes block-level elements like <h1>, <div>, or unordered lists inside a container, the behavior breaks down. The saveXML method applied to a child node often truncates the output prematurely. For instance, if an <h1> element exists within a <p> tag (which is technically invalid HTML but common in raw strings), saveXML on that parent <p> node will only return content up to the first child it encounters, effectively cutting off any subsequent siblings like <h1> tags.

The Limitation of Node-Specific SaveXML

The core issue lies in how DOMDocument handles serialization when targeting a non-document root node. When you call $d->saveXML($node), PHP serializes the XML representation of that specific node and its descendants. If your input string is loaded without flags, DOMDocument attempts to parse it as an HTML fragment. In many cases, it implicitly wraps the content in a <body> or <html> structure during the parsing phase to maintain document validity according to W3C standards.

Attempting to bypass this by targeting a specific child node, such as $d->getElementsByTagName('p')->item(0), works only for flat structures containing text or inline elements. As soon as you introduce a block-level element like <h1> inside the same parent scope, the serialization logic fails to capture the full sibling tree correctly from that specific anchor point. The output becomes truncated because the internal pointer resolution within saveXML does not traverse across certain boundary conditions when starting from a non-root node.

Leveraging Document-Level Serialization

To resolve this without manually reconstructing the DOM tree, the most reliable workaround is to serialize the entire document context rather than a specific fragment. Instead of targeting the first paragraph or body child, you should call saveXML on the document object itself, but with a crucial configuration change.

The solution involves passing the root node explicitly to the serialization method while stripping the outer wrappers programmatically. However, a more direct approach exists within the PHP DOM API: calling $d->saveXML() without passing a specific second argument defaults to serializing the entire document tree, including any auto-generated <html> and <body> tags.

To achieve clean output without these wrappers, you must explicitly request the serialization of the child nodes directly. You can access the children of the <body> tag (or the root fragment if no body was created) and serialize them individually. A robust pattern involves retrieving the first child node of the document's root element and saving that specific subtree:

$fragment = $d->getElementsByTagName('body')->item(0);
if ($fragment && $fragment->hasChildNodes()) {
    // Save the XML starting from the first child node found in the body
    // This often avoids the <html><body> wrapper if configured correctly
    $cleanContent = $d->saveXML($fragment->firstChild, LIBXML_NOEMPTY Elem);
}

However, the most effective fix for the specific truncation issue described is to save the XML of the document node itself but ensure that the initial parsing did not force a full HTML document structure if you intended to handle fragments. If loadHTML was used without flags, it adds the wrappers. To prevent this entirely, pass LIBXML_HTML_NOIMPLIEDTAGS or similar flags depending on your PHP version and specific needs.

Alternatively, if you must work with the existing loaded object where wrappers have already been added implicitly, the safest extraction method is to grab the first child of the <body> element and serialize that node's subtree. This ensures that block-level elements like <h1> are included in their entirety because they are direct children of the target node being serialized.

$targetNode = $d->getElementsByTagName('body')->item(0)->firstChild;
if ($targetNode) {
    $postarray['post_content'] = $d->saveXML($targetNode);
}

Understanding Trade-offs

This approach shifts the responsibility of handling the document root from the parser to the serialization step. By targeting the first child node inside the body, you effectively tell DOMDocument to treat that node as the new root for serialization purposes. This preserves all siblings, including complex block elements, without generating the <html> or outer <body> tags in the final string.

Be aware that this method assumes a valid document structure where a <body> tag exists and contains at least one child. If your input HTML is malformed or lacks standard tags, you may need to inspect the childNodes collection of the root element directly to find the first non-null node to serialize. Always verify that hasChildNodes() returns true before attempting serialization to avoid empty outputs.

For production environments dealing with raw content ingestion, ensuring consistent parsing flags during loadHTML is critical. If you control the initial load, passing specific constants can prevent the automatic addition of wrappers, making the subsequent extraction step much simpler and less prone to truncation errors.

Our network