Home > OS >  Replace a whole div code (with divs inside) with different code using php
Replace a whole div code (with divs inside) with different code using php

Time:10-22

I am getting a code of a page using ob_buffer and i try to replace all divs inside the page that contain the class locked-content.

While it's easy with jquery the problem is that with php is a bit harder. Let say for example i have this html code

<div class='class'> cool content </div>

<div class='class more-class life-is-hard locked-content'>

    <div class='cool-div'></div>
    <div class='anoter-cool-div'></div>

    some more code here

</div>

<div class='class'> cool content </div>

Now it seems like a complex task, I think i need to detect somehow how many divs are open after the div with the class 'locked-content' and then count how many closed div there are and when the wanted div was closed and then replace the code with new code while looping the code in case the div exists more than once.

Anyone has an idea on how to do something like this? Thanks

CodePudding user response:

You can use the dom php extension for that. This makes it pretty easy to select/count/manipulate html nodes.

Here the docs: https://www.php.net/manual/en/intro.dom.php

CodePudding user response:

You can do it via DOMXPath:

$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXPath($dom);
$node = $xpath->query('//div[contains(@class, "locked-content")]');

foreach ($nodes as $node) {
    foreach ($node->childNodes as &$cNode) {
        if ($cNode instanceOf DOMElement && $cNode->tagName === 'div') {
            $cNode->replaceWith(/* Whatever */);
        }
    }
}
  •  Tags:  
  • php
  • Related