2014-07-12 5 views
1

url로 html을로드합니다. 그 생성 DOMDocument를DOMDocument 및 부모 태그 삭제

libxml_use_internal_errors(true); // disable errors 

$oHtml = new DOMDocument(); 

if (!$oHtml->loadHTML($this->getHtml($aData['href']))) { 
    return false; 
} 

다음 단계는 우리의 경우 이미지 코드에서 ... fancybox 또는 다른 때에 popUp 링크를 삭제하는 것입니다 후

<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> 

입니다 그리고 우리는 ... 그것을 위해 우리의 방법을 실행

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

방법 ...

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); 
      } 
     } 
    } 

지금 질문 ...이 코드는 작동하지만 왜 나는 얻지 못합니다! clearPopUpLink()가 모든 "이미지"로 완료되면 태그가있는 OLD 코드가 아닌 이유는 무엇입니까? 나는 (처음 조사를 시작할 때) -> insertBefore(), 그 다음 -> removeChild()를 사용하려고했다. 먼저 간단한 (편집 한) 이미지 BEFOR 현재 이미지 (<a>)를 추가 한 후 이전 노드 이미지 (<a>)를 삭제하십시오. 그러나! 그것은 작동하지 않는다, 그것은 각 두번째에 단지하고 있었다 (첫번째는 정확하게 행해졌 다).

간단한 질문을 드리겠습니다. 올바른 방법으로 어떻게해야합니까? 아래 코드 (clearPopUpLink)가 충분하다고 생각하지 않기 때문에 ... 솔루션을 제안하십시오.

+0

이것은 앵커를 드롭하지만 이미지를 유지하겠습니까? –

답변

2

흠, 저는 이것을 위해 트러스티 XPath를 사용하고 앵커가 제거되었는지 확인하십시오. 표시 한 코드가 그 사실을 명확하게 나타내지는 않습니다 (테스트하지 않았습니다).

$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(); 
+0

예상대로. 감사합니다, 간단하고 우아한 ... – user1954544