I intend to make some changes in an HTML document, like remove, replace, append some nodes.
I have several arrays with same structure like the following example
$patterns[] = array(
'xpath' => '/html/body/div/p',
'insert' => $new_a,
'task' => 'replace'
);
...
$patterns[] = array(
'xpath' => '/html/body/header',
'insert' => $new_b,
'task' => 'remove'
);
and I use the following snippet
$dom = new DOMDocument();
if ((empty($html) !== true) && ($dom->loadHTML($html) === true))
{
$dom->formatOutput = true;
// Use DomXPath
$xpath = new DomXPath($dom);
// Process Dom changes
foreach ($patterns as $key => $value)
{
$xpath_results = $xpath->query($patterns[$key]['xpath']);
if ($xpath_results->length)
{
// Assign some values
$xpath_results = $xpath_results->item(0);
$task = $patterns[$key]['task'];
$replacement = $patterns[$key]['insert'];
if ($task != 'remove')
{
// Create the replacement
$newNode = $dom->createDocumentFragment();
$newNode->appendXML($replacement);
}
switch ($task)
{
case 'remove':
$xpath_results->parentNode->removeChild($xpath_results);
break;
case 'replace':
$xpath_results->parentNode->replaceChild($newNode, $xpath_results);
break;
case 'append':
$xpath_results->appendChild($newNode);
break;
case 'prepend':
$xpath_results->parentNode->insertBefore($newNode, $xpath_results);
break;
}
}
}
// Save Dom
$html = $dom->saveXML($dom->documentElement);
}
I would like your expert comments about if this is done the right way. The foreach
to loop through the array elements, the switch
to choose what will be done and if the use of createDocumentFragment
is appropriate in this case.