2010-08-05 91 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到文件。因此,一旦您用提示更新了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

如果你想保存一樣,你可以使用dom_import_simplexml轉換爲一個DOMElement並保存:

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

所以上面看着我的代碼,這將節省我的更新$ XML對象的任何$ filename是? – ThinkingInBits 2010-08-05 19:37:49

+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 2010-08-05 19:41:54

+0

好吧,實際上現在與$ dom-> save($ filename)一起工作... 謝謝! – ThinkingInBits 2010-08-05 19:45:19

相關問題