2012-02-16 82 views
4

首先,我需要通过xml文档中的特定子节点值查找父节点;然后将一些特定的子节点从父节点复制到另一个xml文档。PHP将xml节点从一个文档复制到另一个文档

例如:

DESTINATION FILE: ('destination.xml') 
<item> 
    <offerStartDate>2012-15-02</offerStartDate> 
    <offerEndDate>2012-19-02</offerEndDate> 
    <title>Item Title</title> 
    <rrp>14.99</rrp> 
    <offerPrice>9.99</offerPrice> 
</item> 

SOURCE FILE: ('source.xml') 
<items> 
    <item> 
     <title>Item A</title> 
     <description>This is the description for Item A</description> 
     <id>1003</id> 
     <price> 
      <rrp>10.00</rrp> 
      <offerPrice>4.99</offerPrice> 
     </price> 
     <offer> 
      <deal> 
       <isLive>0</isLive> 
      </deal> 
     </offer> 
    </item> 
    <item> 
     <title>Item B</title> 
     <description>This is the description for Item B</description> 
     <id>1003</id> 
     <price> 
      <rrp>14.99</rrp> 
      <offerPrice>9.99</offerPrice> 
     </price> 
     <offer> 
      <deal> 
       <isLive>1</isLive> 
      </deal> 
     </offer> 
    </item> 
    <item> 
     <title>Item C</title> 
     <description>This is the description for Item C</description> 
     <id>1003</id> 
     <price> 
      <rrp>9.99</rrp> 
      <offerPrice>5.99</offerPrice> 
     </price> 
     <offer> 
      <deal> 
       <isLive>0</isLive> 
      </deal> 
     </offer> 
    </item> 

我想找到有它的子节点<isLive>值设置为 “1” 的父节点<item>。然后将父节点的其他子节点复制到目标xml。

例如如果父节点<item>将其子节点<isLive>设置为1.复制<title><rrp><offerPrice>节点及其值,并将它们作为子节点添加到目标文件,如上所示。

如果我没有正确使用它们,请原谅我的技术术语。

非常感谢帮助家伙!

+0

我假设你destination.xml有一个项目的根节点,太? – Gordon 2012-02-16 12:10:31

+0

是的,它''。现在处理它,谢谢 – echez 2012-02-16 14:30:36

回答

6

用SimpleXML(demo):

$dItems = simplexml_load_file('destination.xml'); 
$sItems = simplexml_load_file('source.xml'); 
foreach ($sItems->xpath('/items/item[offer/deal/isLive=1]') as $item) { 
    $newItem = $dItems->addChild('item'); 
    $newItem->addChild('title', $item->title); 
    $newItem->addChild('rrp', $item->price->rrp); 
    $newItem->addChild('offerprice', $item->price->offerPrice); 
} 
echo $dItems->saveXML(); 

随着DOM(demo):

$destination = new DOMDocument; 
$destination->preserveWhiteSpace = false; 
$destination->load('destination.xml'); 
$source = new DOMDocument; 
$source->load('source.xml'); 
$xp = new DOMXPath($source); 
foreach ($xp->query('/items/item[offer/deal/isLive=1]') as $item) 
{ 
    $newItem = $destination->documentElement->appendChild(
     $destination->createElement('item') 
    ); 
    foreach (array('title', 'rrp', 'offerPrice') as $elementName) { 
     $newItem->appendChild(
      $destination->importNode(
       $item->getElementsByTagName($elementName)->item(0), 
       true 
      ) 
     ); 
    } 
} 
$destination->formatOutput = true; 
echo $destination->saveXml(); 
+0

他们都打印php文件上的新数据,但既不保存到目标xml。任何想法请问? – echez 2012-02-16 15:17:31

+0

@echez我留下最后一点给你找出他们各自在PHP手册中的文档;) – Gordon 2012-02-16 15:26:59

+0

够公平的。非常感谢。如果我的答案解决了您的问题,我会发布开发 – echez 2012-02-16 15:47:58

相关问题