ech*_*hez 4 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>
Run Code Online (Sandbox Code Playgroud)
和
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>
Run Code Online (Sandbox Code Playgroud)
我想找到将<item>其子节点<isLive>值设置为"1" 的父节点.然后将父节点的其他子节点复制到目标xml.
例如,如果父节点<item>都有其子节点<isLive>设置为1复制<title>,<rrp>以及<offerPrice>节点和它们的值,并将其添加到目标文件的子节点,如上图所示.
请原谅我的技术术语,如果我没有正确使用它们.
非常感谢帮助人员!
使用SimpleXml(演示):
$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();
Run Code Online (Sandbox Code Playgroud)
使用DOM(演示):
$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();
Run Code Online (Sandbox Code Playgroud)