2010-03-01 4 views

답변

18

SimpleXML은 이것을 수행 할 수 없으므로 DOM을 사용해야합니다. 좋은 소식은 DOM과 SimpleXML이 같은 동전 인 libxml의 양면이라는 것입니다. 따라서 SimpleXML을 사용하든 DOM을 사용하든 동일한 트리에서 작업하고 있습니다. 다음은 예입니다 :

$thing = simplexml_load_string(
    '<thing> 
     <node n="1"><child/></node> 
    </thing>' 
); 

$dom_thing = dom_import_simplexml($thing); 
$dom_node = dom_import_simplexml($thing->node); 
$dom_new = $dom_thing->appendChild($dom_node->cloneNode(true)); 

$new_node = simplexml_import_dom($dom_new); 
$new_node['n'] = 2; 

echo $thing->asXML(); 

당신이에서와로 변환하지 않고 직접 DOM의 방법을 사용할 수 있습니다 SimpleXML을의 확장이 많은, 당신은 SimpleDOM을 시도 할 수 있습니다 그런 종류의를 수행하는 경우 DOM 개체.

include 'SimpleDOM.php'; 
$thing = simpledom_load_string(
    '<thing> 
     <node n="1"><child/></node> 
    </thing>' 
); 

$new = $thing->appendChild($thing->node->cloneNode(true)); 
$new['n'] = 2; 

echo $thing->asXML(); 
+2

+1 DOM을 추천합니다. 나는 simpleXML에 많은 문제가있다. SimpleXML을 사용하지 마십시오. DOM은 훨씬 강력하고 사용하기가 어렵지 않습니다. – Keyo

+0

이것도 중요하므로주의해야합니다. 내 스크립트를 DOM으로 다시 작성하는 데 30 분을 보내는 것은 유감스럽지 않습니다. 이제는 훨씬 더 직선적이며 유지하기가 쉽습니다. – ivkremer

3

SimpleXML을 사용하면 가장 좋은 방법은 해결 방법입니다. 그것은 꽤 보보,하지만 그것을 작동합니다 : 그것은 SimpleXML을 거기 될 것 같지 않습니다 기능에 대한 해결 방법입니다 때문에

// Strip it out so it's not passed by reference 
$newNode = new SimpleXMLElement($xml->someNode->asXML()); 

// Modify your value 
$newnode['attribute'] = $attValue; 

// Create a dummy placeholder for it wherever you need it 
$xml->addChild('replaceMe'); 

// Do a string replace on the empty fake node 
$xml = str_replace('<replaceMe/>',$newNode->asXML(),$xml->asXML()); 

// Convert back to the object 
$xml = new SimpleXMLElement($xml); # leave this out if you want the xml 

, 당신은 내가이 어떤 객체 참조를 깰 것이라고 기대하는 점에 유의해야합니다 당신 있다면이 시점까지 정의했다.

+0

이 대답을 너무 좋아해서 간단합니다. '$ newNode-> asXML()'이 원시 XML 조각 대신 XML 헤더를 작성하고 있었기 때문에 대답을 약간 수정해야했습니다. $ domNode = dom_import_simplexml ($ newNode); $ xml = str_replace ('', $ domNode-> ownerDocument-> saveXML ($ domNode), $ xml-> asXML()); – AaronP

관련 문제