3 回答
TA贡献1851条经验 获得超5个赞
使用 DOM,您可以将位置节点的克隆附加到相应的项目元素。
$document = new DOMDocument();
$document->load($url);
$xpath = new DOMXpath($document);
// iterate the location child of the destino elements
foreach($xpath->evaluate('//destino/location') as $location) {
// iterate the item nodes inside the same parent node
foreach ($xpath->evaluate('parent::*/programas/item', $location) as $item) {
// append a copy of the location to the item
$item->appendChild($location->cloneNode(TRUE));
}
}
echo $document->saveXML();
TA贡献1865条经验 获得超7个赞
使用 SimpleXML,您可以只使用对象表示法来访问文档的各种元素,这样就不再需要 XPath 并且还可以使代码更具可读性...
$url = file_get_contents("archive.xml");
$xml = simplexml_load_string($url);
foreach ($xml->destino as $destino) {
// Process each item
foreach ( $destino->programas->item as $item ) {
// Set the location from the destino location value
$item->location = (string)$destino->location;
}
}
header('Content-Type: application/xml');
echo $xml->asXML();
需要注意的一点是,在使用 SimpleXML 时,根节点(<destinos>在本例中)是$xml对象。这就是$xml->destino访问<destino>元素的原因。
TA贡献1815条经验 获得超13个赞
一种选择是将xpath与addChild与位置值一起使用:
$url = file_get_contents("archive.xml");
$xml = simplexml_load_string($url);
$changes = $xml->xpath("/destinos/destino");
foreach ($changes as $change) {
$text = (string)$change->location;
foreach ($change->xpath("programas/item") as $i) {
$i->addChild("location", $text);
}
}
header('Content-Type: application/xml');
echo $xml->asXML();
输出
<destinos>
<destino>
<location>Spain</location>
<programas>
<item><location>Spain</location></item>
<item><location>Spain</location></item>
</programas>
</destino>
<destino>
<location>France</location>
<programas>
<item><location>France</location></item>
<item><location>France</location></item>
</programas>
</destino>
</destinos>
- 3 回答
- 0 关注
- 151 浏览
添加回答
举报