【问题标题】:PHP, find element of XML and do something with itPHP,找到 XML 的元素并用它做一些事情
【发布时间】:2020-04-20 10:12:52
【问题描述】:

我遇到了以下问题,我有一个 import.xml,其中包含一个示例内容,例如

<abc></abc>
<lable_def name="Label" x="100" y="200" z="300"></label_def>
<abcd></abcd>
....
...

现在我想要以下内容:

if the tag is = <lable_def name"Label" 
than delete X and Y Tags
and value of Z minus 6
and add the tag haschanged="1"

整个 XML 应该保存为 new.xml,其中包含所有原始内容,但有一些更改,例如:

<abc></abc>
<lable_def name="Label" z="294" haschanged="1"></label_def>
<abcd></abcd>
....
...

如何用 PHP 解决这个问题?

【问题讨论】:

    标签: php xml


    【解决方案1】:

    通过使用 DOM 等 XML API 之一。 Xpath 表达式允许您获取 DOM 的一部分。

    $xml = <<<'XML'
    <foo>
    <abc></abc>
    <label_def name="Label" x="100" y="200" z="300"></label_def>
    <abcd></abcd>
    </foo>
    XML;
    
    // bootstrap the DOM document
    $document = new DOMDocument();
    $document->loadXML($xml);
    $xpath = new DOMXpath($document);
    
    // find any element "label_def" with the "name" attribute "Label"
    foreach ($xpath->evaluate('//label_def[@name="Label"]') as $label) {
       // remove x and y attributes
       $label->removeAttribute('x');
       $label->removeAttribute('y');
       // decrease z attribute
       $label->setAttribute('z', $label->getAttribute('z') - 6);
       // add haschanged attribute 
       $label->setAttribute('haschanged', '1');
    }
    
    echo $document->saveXML();
    

    输出:

    <?xml version="1.0"?>
    <foo>
    <abc/>
    <label_def name="Label" z="294" haschanged="1"/>
    <abcd/>
    </foo>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-02
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      • 2012-05-08
      • 2014-12-29
      • 2020-10-06
      相关资源
      最近更新 更多