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);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
array ( 0 => array ( 'item' => 'Title 1', 'data' => 'some data and divs here 1', ), 1 => array ( 'item' => 'Title 2', 'data' => 'some data and divs here 2', ), 2 => array ( 'item' => 'Title 2', 'data' => 'some data and divs here 3', ), 3 => array ( 'item' => 'Title 3', 'data' => 'some data and divs here 4', ), 4 => array ( 'item' => 'Title 3', 'data' => 'some data and divs here 5', ), 5 => array ( 'item' => 'Title 3', 'data' => 'some data and divs here 6', ), )

preferences:
92.69 ms | 408 KiB | 5 Q