3v4l.org

run code in 300+ PHP versions simultaneously
<?php $html = '<h1>Title 1</h1> <div class="items">some data and divs here 1</div> <h1>Title 2</h1> <div class="items">some data and divs here 2</div> <div class="items">some data and divs here 3</div> <h1>Title 3</h1> <div class="items">some data and divs here 4</div> <div class="items">some data and divs here 5</div> <div class="items">some data and divs here 6</div>'; $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXpath($doc); $domNodeList = $xpath->query('/html/body/h1'); $result = []; foreach($domNodeList as $element) { // Save the h1 $item = $element->nodeValue; // Loop the siblings unit the next h1 while ($element = $element->nextSibling) { if ($element->nodeName === "h1") { break; } // if Node is a DOMElement if ($element->nodeType === 1) { $result[] = ['item' => $item, 'data' => $element->nodeValue]; } } } var_export($result);

preferences:
24.05 ms | 404 KiB | 5 Q