DOMDocument and remove the parent tag

We load html at URL. After that, a DOMDocument is created.

libxml_use_internal_errors(true); // disable errors $oHtml = new DOMDocument(); if (!$oHtml->loadHTML($this->getHtml($aData['href']))) { return false; } 

The next step is to remove fancybox or other popUp links ... In our case, the image code

 <a onclick="return hs.expand(this)" href="http://domain.com/uploads/09072014106.jpg"> <img title="Some title" alt="Some title" src="http://domain.com/uploads/thumbs/09072014106.jpg"> </a> 

And we execute our method for it ...

 $this->clearPopUpLink($oHtml); // delete parent <a tag.... 

Method...

 private function clearPopUpLink($oHtml) { $aLink = $oHtml->getElementsByTagName('a'); if (!$aLink->length) { return false; } for ($k = 0; $k < $aLink->length; $k++) { $oLink = $aLink->item($k); if (strpos($oLink->getAttribute('onclick'), 'return hs.expand(this)') !== false) { // <a onclick="return hs.expand(this)" href="http://domain.com/uploads/posts/2014-07/1405107411_09072014106.jpg"> // <img title="Some title" alt="Some title" src="http://domain.com/uploads/posts/2014-07/thumbs/1405107411_09072014106.jpg"> // </a> $oImg = $oLink->firstChild; $oImg->setAttribute('src', $oLink->getAttribute('href')); // set img proper src // $oLink->parentNode->removeChild($oLink); // $oLink->parentNode->replaceChild($oImg, $oLink); $oLink->parentNode->insertBefore($oImg); // replacing!?!?!?! // echo $oHtml->ownerDocument->saveHtml($oImg); } } } 

Now questions ... This code works, but I do not get WHY! Why, when running clearPopUpLink () with all the "images", does it have no OLD code with tags? I tried using (for the first time at the start of the study) -> insertBefore (), after which -> removeChild (). First, add a simple (edited) image of the current BEFOR image (with <a> ), then delete the old node image (with <a> ). BUT! It does not work, it executed only every second (each of them was executed correctly).

So let me ask a simple question, how to do it right? Because I donโ€™t think the code below (clearPopUpLink) is correct enough ... Please suggest your solutions.

+1
source share
1 answer

Hmm, I would use Trustey XPath for this and make sure the binding is removed; the code you showed does not exactly make it obvious (I have not tested it).

 $xpath = new DOMXPath($doc); foreach ($xpath->query('//a[contains(@onclick, "return hs.expand(this)")]/img') as $img) { $anchor = $img->parentNode; $anchor->parentNode->insertBefore($img, $anchor); // take image out $anchor->parentNode->removeChild($anchor); // remove empty anchor } echo $doc->saveHTML(); 
+2
source

All Articles