php - XML 将值从父级更改为子级
问题描述
我有这个 XML:
<destinos>
<destino>
<location>Spain</location>
<programas>
<item></item>
<item></item>
</programas>
</destino>
<destino>
<location>France</location>
<programas>
<item></item>
<item></item>
</programas>
</destino>
</destinos>
我需要在每个“项目”中包含或复制“位置”的值,但我无法这样做。
<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>
我对PHP一无所知,我一直在阅读,但找不到解决方案。
如果有人可以帮助我并解释我将非常感激。
我的代码:
$url = file_get_contents("archive.xml");
$xml = simplexml_load_string($url);
$changes = $xml->xpath("//*[starts-with(local-name(), 'item')]");
foreach ($changes as $change)
$change[0] = $xml->destinos->destino->location;
header('Content-Type: application/xml');
echo $xml->asXML();
解决方案
使用 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();
推荐阅读
- ios - XMPP:聊天性能下降列表
- c - 出现错误:多字符字符常量 [-Werror,-Wmultichar]
- c++ - (const_cast) 有什么区别
没有? - ubuntu - 使用 ubuntu 服务器时出现 MaxRetryError
- spring - 项目可以使用非发布版本的依赖项投入生产吗?
- python - 如何为 Copy From 查询指定列
- php - cpanel文件上传问题
- javascript - 带有 javascript 的 PDF 导出带有扁平表单字段的 PDF 并重置 pdf
- graphviz - 在 graphviz 边缘中添加颜色渐变
- javascript - 如何根据选中的复选框激活文本框并使用 Vue js 和 javascript 中的 v-model 从文本框中获取值?