Get html between comments block Simple HTM DOM
Asked Answered
R

1

6

How can I take a block of DOM by identify its 'comment' tag, like

<!-- start block -->
<p>Hello world etc</p>
<div>something</div>
<!-- end of block -->

I'm using Simple PHP DOM parser, but the doc is incomplete, http://simplehtmldom.sourceforge.net/manual.htm. It's fine if I can do it with pure PHP.

Renn answered 22/4, 2015 at 13:1 Comment(1)
This is probably one of the times when it's ok to use regex.Matrilineal
O
1

You can try to iterate thru the elements first, then if you found the starting comment, skip it first, then add a flag which starts the concatenation of the next elements. If you reach the end-point, stop the concatenation:

$html_string = '<!-- start block -->
<p>Hello world etc</p>
<div>something</div>
<div>something2</div>
<!-- end of block -->
<div>something3</div>
';

$html = str_get_html($html_string);
// start point
$start = $html->find('*');
$output = ''; $go = false;
foreach($start as $e) {

    if($e->innertext === '<!-- start block -->') {
        $go = true;
        continue;
    } elseif($e->innertext === '<!-- end of block -->') {
        break;
    }

    if($go) {
        $output .= $e;
    }   
}

echo $output;
Oscaroscillate answered 22/4, 2015 at 13:23 Comment(1)
@EltonJamie yeah just continue to get those after the flag has started, once the ending is found, then break itOscaroscillate

© 2022 - 2024 — McMap. All rights reserved.