简体   繁体   English

使用PHP动态更新XML

[英]Updating XML dynamically with PHP

So this might seem like a dumb question, but I can not find a single example of it. 因此,这似乎是一个愚蠢的问题,但我找不到单个示例。 What I am looking for is a way to update an XML file WITHOUT knowing the names or attributes or anything about the file per say to hard code. 我正在寻找的是一种在不知道名称或属性或与硬编码有关的文件内容的情况下更新XML文件的方法。

How I intend to do this, is I have php that reads the xml file, and creates a html form with a text field for each name + attribue combo ex: 我打算如何执行此操作,是让我的php读取xml文件,并为每个名称+属性组合ex创建一个带有文本字段的html表单:

<Tools>
        <RangeScrew Red="255" Green="192" Blue="203"/>
        <RangeRing Red="255" Green="192" Blue="203"/>
</Tools>

If it loaded something like this, it would look something like this: 如果加载了这样的内容,它将看起来像这样:

示例生成的HTML

So from here say I changed one of the values and clicked update value, I can pass any info to the next function, such as the name of the attribute, the node of the xml tree, or the whole node/parent combo. 因此,从这里说我更改了一个值并单击了更新值,就可以将任何信息传递给下一个函数,例如属性名称,xml树的节点或整个节点/父组合。 Since it will be heavily nested XML files. 由于它将大量嵌套XML文件。

There is a ton of examples where people hard code the path to these nodes to update them but I can't find a dynamic way. 有大量的示例,人们用硬编码这些节点的路径来更新它们,但是我找不到动态的方法。 Any suggestions if I wanted to update? 有什么建议要更新吗? lets say if the example I gave was nested several deep. 可以说我给出的示例是否嵌套了多个深度。

A very simple example of what you can do with SimpleXML and updating an element in any position. 一个非常简单的示例,说明您可以使用SimpleXML进行操作并在任意位置更新元素。

So if you wanted to update the value of the Blue attribute of <RangeScrew> , you can store a path of /Tools/RangeScrew/@Blue , which defines where it is in the hierarchy with @ to denote an attribute (this also happens to be an XPath expression). 所以,如果你想更新的蓝属性的值<RangeScrew>可以存放的路径/Tools/RangeScrew/@Blue ,它定义了它与层次@来表示一个属性(这也恰好是XPath表达式)。 You can then use this to locate the value to update. 然后,您可以使用它来定位要更新的值。

$source = '<Tools>
        <RangeScrew Red="255" Green="192" Blue="203"/>
        <RangeRing Red="255" Green="192" Blue="203"/>
</Tools>';

$path = "/Tools/RangeScrew/@Blue";
$value = "10";

$xml = simplexml_load_string($source);

// xpath returns a list of matches, so use [0] to get the first entry
$element = $xml->xpath($path)[0];
// Update the value (using [0] calls the magic method which allows you to set
// the value
$element[0] = $value;

echo $xml->asXML();

So this sets the Blue attribute to 10 and outputs the resultant XML... 因此,这会将Blue属性设置为10并输出结果XML。

<?xml version="1.0"?>
<Tools>
        <RangeScrew Red="255" Green="192" Blue="10"/>
        <RangeRing Red="255" Green="192" Blue="203"/>
</Tools>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM