Skip to content

Instantly share code, notes, and snippets.

@herveguetin
Last active February 15, 2023 05:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save herveguetin/8844a08d6f8380fe68fe to your computer and use it in GitHub Desktop.
Save herveguetin/8844a08d6f8380fe68fe to your computer and use it in GitHub Desktop.
Replace HTML tags using PHP DOM objects and Zend_Dom_Query
<?php
$replacedTags = array(
'dt' => array( // <dt> tag is replaced by...
'tag' => 'div', // ... <div> tag...
'attributes' => array( // ... with these attributes
'class' => 'some-class',
'id' => 'some_id',
'data-something' => 'some-value'
)
),
'dd' => array(
'tag' => 'div',
'attributes' => array(
'class' => 'some-other-class',
'id' => 'some_other_id',
'data-something' => 'some-other-value'
)
)
);
// Create a new item that will contain our new DOM elements
$newItem = new DOMDocument();
// Create a Zend_Dom_Query object in order to find tags to replace
$html = '<dt>Some DT</dt><dd><div>Some DD content</div></dd>'; // Your source HTML
$html = utf8_decode($html);
$domQuery = new Zend_Dom_Query($html);
// Create DOM content for $newItem
foreach ($replacedTags as $tag => $config) {
// Find DOM elements matching the tag to replace
$searchedDomElements = $domQuery->query($tag);
foreach ($searchedDomElements as $searchedDomElement) {
// Create a new DOM element in $newItem with new tag...
$newDomElement = $newItem->createElement($config['tag']);
// ... and set updated attributes on this new DOM element
foreach($config['attributes'] as $attribute => $value) {
$newDomElement->setAttribute($attribute, $value);
}
// Inject all child nodes from $searchedElement into the new DOM element
$children = $searchedDomElement->childNodes;
foreach($children as $child) {
// Create a DOM element in $newItem that is a clone of $child and with all $child's nodes...
$newDomElementChild = $newItem->importNode($child, true);
// ... and append this DOM element to the new DOM element
$newDomElement->appendChild($newDomElementChild);
}
// Once the new DOM element is ready, append it to the $newItem
$newItem->appendChild($newDomElement);
}
}
// Generate HTML out of complete $newItem
$updatedHtml = $newItem->saveHTML();
return utf8_encode($updatedHtml);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment