PHP将xml节点从一个文档复制到另一个文档
首先,我需要在xml文档中通过特定的子节点值找到父节点;然后将一些特定的子节点从父节点复制到另一个xml文档 例如:PHP将xml节点从一个文档复制到另一个文档,php,xml,xpath,simplexml,Php,Xml,Xpath,Simplexml,首先,我需要在xml文档中通过特定的子节点值找到父节点;然后将一些特定的子节点从父节点复制到另一个xml文档 例如: DESTINATION FILE: ('destination.xml') <item> <offerStartDate>2012-15-02</offerStartDate> <offerEndDate>2012-19-02</offerEndDate> <title>Item T
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>
目标文件:('DESTINATION.xml')
2012-15-02
2012-19-02
项目名称
14.99
9.99
及
源文件:('SOURCE.xml')
项目A
这是项目A的说明
1003
10
4.99
0
B项
这是项目B的说明
1003
14.99
9.99
1.
项目C
这是项目C的说明
1003
9.99
5.99
0
我想找到将其子节点
值设置为“1”的父节点
。然后将父节点的其他子节点复制到目标xml
e、 g.如果父节点
的子节点
设置为1。复制
、
和
节点及其值,并将它们作为子节点添加到目标文件中,如上所示
如果我没有正确使用它们,请原谅我的技术术语
非常感谢你们的帮助 使用SimpleXml():
使用DOM():
我假设您的destination.xml也有一个items根节点?是的,它有“”。现在,他们都在php文件上打印新数据,但都没有保存到目标xml。有什么想法吗?@echez我把最后一点留给您,让您从PHP手册中各自的文档中了解;)@echez如果我的答案解决了你的问题,我很高兴你能通过勾选左边投票控制旁边的绿色复选标记来接受它。谢谢。非常感谢你的帮助@Gordon。我确实用“echo$destination->saveXml('destination.xml');”对保存位进行了排序并且必须更改服务器上的文件权限,以便我可以写入该文件。如果两个文档具有不同的名称空间,该怎么办?我猜DOM importNode()也会获取名称空间并添加到节点中。如果我们不想复制命名空间呢?
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>
$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();
$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();