Exa" /> Exa" /> Exa"/>

How to change the tag itself in QueryPath?

427 Views Asked by At

I would like to change the tag itself, identified in QueryPath. To be specific, I would like to convert an anchor tag like this
<a href="abc.html">Example</a>
into
<?php Blah-Blah ?>Example</a>
or
<?php Blah-Blah2 ?>

I can find the anchor tag and retrieve its element:
$qp->find('a[href]'); $href = $qp->attr('href');
but then, is there any way to change/replace the tag itself in QueryPath?

Alternatively it is fine by me to wrap the component with <div id="specific"> tag - if this is possible, I suppose I can search for it with $qp->top('div[id="specific"]');, then can replace the entire child (the anchor tag and its element) with the php code.

However, I have failed to find either way in QueryPath...

1

There are 1 best solutions below

5
Sajjad Shirazi On
function renameTag( DOMElement $oldTag, $newTagName ) {
   $document = $oldTag->ownerDocument;

   $newTag = $document->createElement($newTagName);
   $oldTag->parentNode->replaceChild($newTag, $oldTag);

   foreach ($oldTag->attributes as $attribute) {
       $newTag->setAttribute($attribute->name, $attribute->value);
   }
   foreach (iterator_to_array($oldTag->childNodes) as $child) {
       $newTag->appendChild($oldTag->removeChild($child));
   }
   return $newTag;
}

and

$qp->find('a[href]')->each(function($index,$element){
   renameTag($element,'?php');
});

you have to iterate for all elements in the query ...