Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6782921
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T16:48:07+00:00 2026-05-26T16:48:07+00:00

Assuming you have a DOM tree with nested tags, I would like to clean

  • 0

Assuming you have a DOM tree with nested tags, I would like to clean the DOM object up by removing duplicates. However, this should only apply if the tag only has a single child tag of the same type. For example,

Fix <div><div>1</div></div> and not <div><div>1</div><div>2</div></div>.

I’m trying to figure out how I could do this using PHP’s DOM extension. Below is the starting code and I’m looking for help figuring out the logic needed.

<?php

libxml_use_internal_errors(TRUE);

$html = '<div><div><div><p>Some text here</p></div></div></div>';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadHTML($html);

function dom_remove_duplicate_nodes($node)
{
    var_dump($node);

    if($node->hasChildNodes())
    {
        for($i = 0; $i < $node->childNodes->length; $i++)
        {
            $child = $node->childNodes->item($i);

            dom_remove_duplicate_nodes($child);
        }
    }
    else
    {
        // Process here?
    }
}

dom_remove_duplicate_nodes($dom);

I collected some helper functions that might make it easier to work the DOM nodes like JavaScript.

function DOM_delete_node($node)
{
    DOM_delete_children($node);
    return $node->parentNode->removeChild($node);
}

function DOM_delete_children($node)
{
    while (isset($node->firstChild))
    {
        DOM_delete_children($node->firstChild);
        $node->removeChild($node->firstChild);
    }
}

function DOM_dump_child_nodes($node)
{
    $output = '';
    $owner_document = $node->ownerDocument;

    foreach ($node->childNodes as $el)
    {
        $output .= $owner_document->saveHTML($el);
    }
    return $output;
}

function DOM_dump_node($node)
{
    if($node->ownerDocument)
    {
        return $node->ownerDocument->saveHTML($node);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T16:48:08+00:00Added an answer on May 26, 2026 at 4:48 pm

    You can do this quite easily with DOMDocument and DOMXPath. XPath especially is really useful in your case because you easily divide the logic to select which elements to remove and the way you remove the elements.

    First of all, normalize the input. I was not entirely clear about what you mean with empty whitespace, I thought it could be either empty textnodes (which might have been removed as preserveWhiteSpace is FALSE but I’m not sure) or if their normalized whitespace is empty. I opted for the first (if even necessary), in case it’s the other variant I left a comment what to use instead:

    $xp = new DOMXPath($dom);
    
    //remove empty textnodes - if necessary at all
    // (in case remove WS: [normalize-space()=""])
    foreach($xp->query('//text()[""]') as $i => $tn)
    {
        $tn->parentNode->removeChild($tn);
    }
    

    After this textnode normalization you should not run into the problem you talked about in one comment here.

    The next part is to find all elements that have the same name as their parent element and which are the only child. This can be expressed in xpath again. If such elements are found, all their children are moved to the parent element and then the element will be removed as well:

    // all child elements with same name as parent element and being
    // the only child element.
    $r = $xp->query('body//*/child::*[name(.)=name(..) and count(../child::*)=1]');
    foreach($r as $i => $dupe)
    {
        while($dupe->childNodes->length)
        {
            $child = $dupe->firstChild;
            $dupe->removeChild($child);
            $dupe->parentNode->appendChild($child);
        }   
        $dupe->parentNode->removeChild($dupe);
    }
    

    Full demo.

    As you can see in the demo, this is independent to textnodes and commments. If you don’t want that, e.g. actual texts, the expression to count children needs to stretch over all node types. But I don’t know if that is your exact need. If it is, this makes the count of children across all node types:

    body//*/child::*[name(.)=name(..) and count(../child::node())=1]
    

    If you did not normalize empty textnodes upfront (remove empty ones), then this too strict. Choose the set of tools you need, I think normalizing plus this strict rule might be the best choice.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Assuming I have an element called menu how would I remove this element from
Assuming I have a tree structure UL --LI ---INPUT (checkbox) And I want to
I want to allow drag-and-drop re-ordering of photoshop-like layers. Assuming I have 3 canvas
New to the simple-html-dom-parser and have a question. Assuming $element is an array, how
I have an XML element that looks something like this: <content locale=en> </content> The
Assuming I have an SQL table with this schema: CREATE TABLE( foo INTEGER, bar
Assuming I have only the class name of a generic as a string in
Assuming I have an open source web server or proxy I can enhance, let's
Assuming I have three tables : TableA (key, value) TableB (key, value) TableC (key,
Assuming I have fonts installed which have the appropriate glyphs in them, is there

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.