2014-09-24 126 views
1

我已閱讀了許多有關此主題的相關問題,似乎無法找到一個突出顯示將其保存爲2個單獨的XML文件的問題。更新現有文件時創建新的XML文件

我在上傳電子書時創建了一個新的XML文件。對於這個例子,它將被保存在「new_file.xml」中。同時,我需要將新信息(本示例中爲<product>)添加到名爲「full_collection_file.xml」的完整集合文件中,並將該文件更新。因此,每次上傳新電子書時,「full_collection_file.xml」都會添加一個新的<product>

下面是簡單的「new_file.xml」目前的結構:

$xml = new DomDocument('1.0', 'UTF-8'); 

$message = $xml->createElement('ONIXMessage'); 
$release = $xml->createAttribute('release'); 
$release->value = '3.0'; 
$message->appendChild($release); 

$header = $xml->createElement('Header'); 
$FromCompany = $xml->createElement('FromCompany','My Company'); 
$header->appendChild($FromCompany); 
$FromEmail = $xml->createElement('FromEmail','[email protected]'); 
$header->appendChild($FromEmail); 
$SentDate = $xml->createElement('SentDate','201408181805'); 
$header->appendChild($SentDate); 
$message->appendChild($header); 

$product = $xml->createElement('Product'); 
$RecordReference = $xml->createElement('RecordReference','B00BBE4BFE'); 
$product->appendChild($RecordReference); 
$NotificationType = $xml->createElement('NotificationType','03'); 
$product->appendChild($NotificationType); 
$message->appendChild($product); 

$xml->appendChild($message); 

$xml->save('new_file.xml'); 

也能正常工作創建第一個XML文件(「new_file.xml」),但不管如何我嘗試做內同樣的地區,我似乎無法正確加載和更新「full_collection_file.xml」。我應該試圖單獨完成這兩件事情,而不是同時完成?似乎多餘,但我希望你可以有2個DomDocument文件同時進行。

+0

@Jongware明白了。謝謝。 – 2014-09-29 16:16:39

回答

1

你只需要一個第二DomDocument對象,然後導入新Product節點,並將其追加到所需的位置:

$doc = new DomDocument('1.0', 'UTF-8'); 
$doc->load('full_collection_file.xml'); 
$node = $doc->importNode($product, true); 
$doc->documentElement->appendChild($node); 

顯然,如果你不想在新<Product>節點權full_collection_file.xml的文檔元素,則需要相應地更改最後一行。

+0

importNode是我所缺少的;正在使用大約6行來完成與1的關係。謝謝,我將用完整答案更新問題。 – 2014-09-24 23:18:51

0

從TML更新時間:

$xml = new DomDocument('1.0', 'UTF-8'); 

$message = $xml->createElement('ONIXMessage'); 
$release = $xml->createAttribute('release'); 
$release->value = '3.0'; 
$message->appendChild($release); 

$header = $xml->createElement('Header'); 
$FromCompany = $xml->createElement('FromCompany','My Company'); 
$header->appendChild($FromCompany); 
$FromEmail = $xml->createElement('FromEmail','[email protected]'); 
$header->appendChild($FromEmail); 
$SentDate = $xml->createElement('SentDate','201408181805'); 
$header->appendChild($SentDate); 
$message->appendChild($header); 

$product = $xml->createElement('Product'); 
$RecordReference = $xml->createElement('RecordReference','B00BBE4BFE'); 
$product->appendChild($RecordReference); 
$NotificationType = $xml->createElement('NotificationType','03'); 
$product->appendChild($NotificationType); 
$message->appendChild($product); 

$xml->appendChild($message); 
$xml->save('new_file.xml'); 

$full_xml = new DomDocument('1.0', 'UTF-8'); 
$full_xml->load('full_collection_file.xml'); 
$node = $full_xml->importNode($product, true); 
$full_xml->documentElement->appendChild($node); 
$full_xml->save('full_collection_file.xml');