PHP XML编辑现有的XML并添加数据


PHP XML edit existing xml and add data

所以我有以下xml结构:

<Application>
        <Properties>
            <Property>
                <Name>blabla</Name>
                <Value>123</Value>
            </Property>
        </Properties>
</Application>

我想用PHP添加另一个"Property"子项。例如:

<Application>
        <Properties>
            <Property>
                <Name>blabla</Name>
                <Value>123</Value>
                                <Name>example test</Name>
                <Value>another value</Value>
            </Property>
        </Properties>
</Application>

这是我当前的php代码:

<?php
    $xml = simplexml_load_file("Application.xml"); 
    $sxe = new SimpleXMLElement($xml->asXML()); 
    $properties = $sxe->addChild("Property");
    $properties->addChild("Name", "namehere"); 
    $properties->addChild("Value", "random value here"); 
    $sxe->asXML("Application.xml");
?>

但它只是将其添加到xml的末尾。在</Application>之后,这不是我们想要的。

我希望它将其添加到<Property>子项中。

有人能帮我吗?

您需要在<Application>标记内部遍历到<Properties>标记。

使用xpath()

$propNode = $sxe->xpath('/Application/Properties');
$property = $propNode[0]->addChild('Property');

这是phpfiddle

如果你想把你的孩子添加到一个特定的元素中,你必须这么说:

$properties = $sxe->Properties->addChild("Property");
                    ^^^^^^^^^^

在线演示

如果有多个Properties元素,并且您不想指定第一个元素,则可以使用基于零的数组索引,例如,0用于第一个元素(默认值),1用于第二个元素:

$properties = $sxe->Properties[1]->addChild("Property");

在线演示