- libxml_use_internal_errors: documentation ( source)
<?php
$html = <<<HTML
<div class="somethingelse">content</div>
<div class="product-fields">
<div class="product-field product-field-type-R">
<span class="product-fields-title-wrapper"><span class="product-fields-title"><strong>Related Products</strong></span>
<span title="" class="hasTooltip" data-original-title="<strong>Related Products</strong><br />COM_VIRTUEMART_RELATED_PRODUCTS_TIP"><img alt="Tooltip" src="/j34/media/system/images/tooltip.png"></span></span>
<span class="product-field-display"><a target="blank" title="Test Product 1" href="/j34/index.php/shops/c1/t1-detail">Test Product 1</a></span><span class="product-field-desc">Custom prototype for related products</span>
</div>
<div class="mickmackusa">Not the drone you're looking for</div>
<div class="product-field matrix-agent-smith product-field-type-R">
<span>Find them and destroy them</span>
</div>
</div>
<div class="someothercontainer">Text</div>
HTML;
$getRelatedProduct = "Flashy, shiny, new";
libxml_use_internal_errors(true);
$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$element = $dom->createElement('div', $getRelatedProduct);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query("//div[contains(@class, 'product-fields')]/div[contains(@class, 'product-field') and contains(@class, 'product-field-type-R')]");
for ($i = $nodes->length - 1; $i >= 0; --$i) { // when removing nodes from DOM, work in reverse order for stability
$node = $nodes->item($i);
if ($i) {
//$trailing_whitespace = $node->nextSibling;
$node->parentNode->removeChild($node); // remove any qualifying element that IS NOT the first element
//$trailing_whitespace->parentNode->removeChild($trailing_whitespace); // optionally remove line returns after removed tags
} else {
$node->parentNode->replaceChild($element, $node); // replace the first element with the generated element
}
}
echo $dom->saveHTML();