首页 > 解决方案 > 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();

标签: phpxml

解决方案


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

推荐阅读