开发者

Modify XML attribute PHP DOM

开发者 https://www.devze.com 2022-12-28 21:50 出处:网络
I have an XML file that looks like this. <collections id=\"my collections\"> <category id=\"my category\">开发者_JAVA技巧;

I have an XML file that looks like this.

<collections id="my collections">
 <category id="my category">开发者_JAVA技巧;
   <record id="my record">
     <title>Some Info</title>
   </record>
 </category>
</collections>

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 :

  • 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>';


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>


Suposing id='my record' is unique in the xml. The hard work is only in the xpath expression.

    $dom = new DomDocument();
    $dom->load('test.xml');
    $xp = new DomXPath($dom);
    $res = $xp->query("//*[@id = 'my record']");
    $res->item(0)->setAttribute('id','2');
    $dom->save('test.xml');
0

精彩评论

暂无评论...
验证码 换一张
取 消