修改XML属性PHP DOM [英] Modify XML attribute PHP DOM

查看:85
本文介绍了修改XML属性PHP DOM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的XML文件.

I have an XML file that looks like this.

<collections id="my collections">
 <category id="my category">
   <record id="my record">
     <title>Some Info</title>
   </record>
 </category>
</collections>

我正在寻找使用PHP DOM和Xpath将上述XML文件中的任何属性替换为新属性的方法. 任何帮助都将受到高度赞赏

I am looking for away to replace any attribute in the above XML file with a new attribute,Using PHP DOM and Xpath. Any help is highly appreciated

推荐答案

不确定要执行的操作,但总体思路是:

Not sure what you want to do exactly, but the general idea is :

  • 您必须实例化 DOMDocument
  • 并使用它加载XML字符串: DOMDocument::loadXML
  • 然后,您必须实例化 DOMXpath 上的那个文件
  • 并使用它来查询文档: DOMXPath::query
  • 您找到了一个您感兴趣的节点,就可以对其进行操作
    • You must instanciate DOMDocument
    • and load your XML strings with it : DOMDocument::loadXML
    • Then, you must instanciate DOMXpath on that document
    • And use it to query the document : DOMXPath::query
    • One you have found the node that interests you, you can manipulate it
      • for example, you can set the value of an attribute : DOMElement::setAttribute


      例如,在这里,您可以使用类似这样的东西:


      Here, for example, you could use some thing like this :

      $str = <<<XML
          <collections id="My Collections">
           <category id="my category">
             <record id="my record">
               <title>Some Info</title>
             </record>
           </category>
          </collections>
      XML;
      
      $dom = new DOMDocument();
      $dom->loadXML($str);
      
      $xpath = new DOMXPath($dom);
      $elements = $xpath->query('//record[@id="my record"]');
      if ($elements->length >= 1) {
          $element = $elements->item(0);
          $element->setAttribute('id', "glop !");
      }
      echo '<pre>' . htmlspecialchars($dom->saveXML()) . '</pre>';
      


      这会将由它标识的节点上的id属性my record替换为"glop !",您将获得以下XML作为输出:


      This will replace the id attribute my record, on the node that's identified by it, by "glop !", and you'd get the following XML as output :

      <?xml version="1.0"?>
      <collections id="My Collections">
           <category id="my category">
             <record id="glop !">
               <title>Some Info</title>
             </record>
           </category>
          </collections>
      

      这篇关于修改XML属性PHP DOM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆