PHP将xml节点从一个doc复制到另一个doc

时间:2012-02-16 12:03:50

标签: php xml xpath simplexml

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

例如:

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> 

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

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

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

非常感谢帮助人员!

1 个答案:

答案 0 :(得分:8)

使用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();