2014-09-24 60 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');