XML将值从父级更改为子级

时间:2019-11-26 18:06:25

标签: 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();

3 个答案:

答案 0 :(得分:1)

一种选择是将xpathaddChild一起使用,并将其与位置值结合使用:

$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>

Php demo

答案 1 :(得分:1)

使用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>元素的原因。

答案 2 :(得分:1)

使用DOM,您可以将位置节点的克隆附加到相应的item元素上。

includes: [io.dropwizard.jetty.MutableServletContextHandler.active-requests,io.dropwizard.jetty.MutableServletContextHandler.active-dispatches,io.dropwizard.jetty.MutableServletContextHandler.active-suspended]