douwu0335 2019-02-02 16:32
浏览 126

使用PHP动态更新XML

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.

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:

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

Example generated 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. Since it will be heavily nested XML files.

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.

  • 写回答

1条回答 默认 最新

  • duannima8347 2019-02-02 21:32
    关注

    A very simple example of what you can do with SimpleXML and updating an element in any position.

    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). 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...

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

报告相同问题?

悬赏问题

  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型