Change XML PHP DOM Attribute

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>

      

I was looking to replace any attribute in the above XML file with a new attribute using PHP DOM and Xpath. Any help is much appreciated

+2


a source to share


2 answers


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


Here, for example, you can use something 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 attribute id

my record

on the node identified by it with " glop !

" and you 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>

      

+5


a source


The id = 'my record' assertion is unique in the xml. The hard work is done 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');

      

+1


a source







All Articles