2011-04-20 12 views
4

좋아, 지금 몇 시간 동안이 작업을 수행하려고 노력 중이므로 여기에 해결책이없는 것 같습니다!PHP DOMDocument가 노드를 문서에서 다른 노드로 이동

DOMDocument가 2 개 있고 문서의 노드를 다른 노드로 옮기고 싶습니다. 나는 두 문서의 구조를 알고 있고 그것들은 같은 유형이다. 그래서 나는 그것들을 합치는데 아무런 문제가 없어야한다.

누구든지 나를 도와 줄 수 있습니까? 더 많은 정보가 필요하시면 알려주세요.

감사합니다.

답변

8

복사 (또는) 당신이 importNode()와 함께 새로운 DOMDocument에 노드를 가져해야 다른 DOMDocument에 노드를 이동하려면을 참조하십시오. 수동에서 가져온 예 : importNode()의 첫 번째 매개 변수는 노드 자체와 두 번째 매개 변수입니다

$orgdoc = new DOMDocument; 
$orgdoc->loadXML("<root><element><child>text in child</child></element></root>"); 
$node = $orgdoc->getElementsByTagName("element")->item(0); 

$newdoc = new DOMDocument; 
$newdoc->loadXML("<root><someelement>text in some element</someelement></root>"); 

$node = $newdoc->importNode($node, true); 
$newdoc->documentElement->appendChild($node); 

는 전체 노드 트리를 가져올 수 있는지 여부를 나타내는 부울입니다.

+2

은 어떻게 DOMDocument를의 모든 노드를 통해 I에게 루프를합니까? 나는 foreach가 작동하도록했다. – AlexV

+0

가장 쉬운 방법은 XPath를 다음과 같이 사용하는 것이다.'$ xpath = new DOMXPath ($ doc); $ allNodes = $ xpath-> query ('// *');' –

0

알 수없는 문서 구조에이 코드를 사용합니다.

$node = $newDoc->importNode($oldDoc->getElementsByTagName($oldDoc->documentElement->tagName)->item(0),true); 
0
<?php 
    protected function joinXML($parent, $child, $tag = null) 
    { 
     $DOMChild = new DOMDocument; 
     $DOMChild->loadXML($child); 
     $node = $DOMChild->documentElement; 

     $DOMParent = new DOMDocument; 
     $DOMParent->formatOutput = true; 
     $DOMParent->loadXML($parent); 

     $node = $DOMParent->importNode($node, true); 

     if ($tag !== null) { 
      $tag = $DOMParent->getElementsByTagName($tag)->item(0); 
      $tag->appendChild($node); 
     } else { 
      $DOMParent->documentElement->appendChild($node); 
     } 

     return $DOMParent->saveXML(); 
    } 
?> 
관련 문제