2010-08-05 4 views
27

그래서 XML 파일의 특정 노드를 검색하고 기존 노드를 설정 해제 한 다음 올바른 데이터가있는 새로운 하위 노드를 삽입하는 코드가 있습니다. 이 새로운 데이터를 simpleXML을 사용하여 실제 XML 파일 내에 저장하는 방법이 있습니까? 그렇지 않다면, 이것을위한 또 다른 효율적인 방법이 있습니까?변경된 SimpleXML 개체를 다시 파일로 저장하는 방법은 무엇입니까?

public function hint_insert() { 

    foreach($this->hints as $key => $value) { 

     $filename = $this->get_qid_filename($key); 

     echo "$key - $filename - $value[0]<br>"; 

     //insert hint within right node using simplexml 
     $xml = simplexml_load_file($filename); 

     foreach ($xml->PrintQuestion as $PrintQuestion) { 

      unset($xml->PrintQuestion->content->multichoice->feedback->hint->Passage); 

      $xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]); 

      echo("<pre>" . print_r($PrintQuestion) . "</pre>"); 
      return; 

     } 

    } 

} 

답변

54

잘 모르겠습니다. asXML() 메서드는 현재 구조를 XML로 파일에 저장하는 선택적 파일 이름을 param으로 허용합니다. 따라서 힌트를 사용하여 XML을 업데이트 한 다음 다시 파일에 저장하십시오. 같은를 저장하려면

// Load XML with SimpleXml from string 
$root = simplexml_load_string('<root><a>foo</a></root>'); 
// Modify a node 
$root->a = 'bar'; 
// Saving the whole modified XML to a new filename 
$root->asXml('updated.xml'); 
// Save only the modified node 
$root->a->asXml('only-a.xml'); 
2

, 당신은 DomElement로 변환 및 저장 dom_import_simplexml를 사용할 수 있습니다

$dom = new DOMDocument('1.0'); 
$dom->preserveWhiteSpace = false; 
$dom->formatOutput = true; 
$dom->loadXML($simpleXml->asXML()); 
echo $dom->saveXML(); 
+0

그래서 위의 내 코드를보고이 내 업데이트 $ XML 객체를 저장할에 어떤 $ 파일 이름은 무엇입니까? – ThinkingInBits

+0

$ dom = new DOMDocument ('1.0')로 변경하려고했습니다. \t \t \t $ dom-> preserveWhiteSpace = false; \t \t \t $ dom-> formatOutput = true; \t \t \t $ dom-> loadXML ($ xml-> asXML()); \t \t \t $ dom-> save ($ filename); 그러나 여전히 파일에 업데이트가 없습니다. – ThinkingInBits

+0

좋습니다. 실제로 $ dom-> save ($ filename)로 작동합니다 ... 고마워요! – ThinkingInBits

관련 문제