SoFunction
Updated on 2025-03-10

Detailed explanation of how to operate XML by PHP native DOM object

1. Create

Create a new XML file and write some data into this XML file.

/*
  * Create an xml file
  */
 
$info = array(
 array('obj' => 'power','info' => 'power is shutdown'),
 array('obj' => 'memcache','info' => 'memcache used than 90%'),
 array('obj' => 'cpu','info' => 'cpu used than 95%'),
 array('obj' => 'disk','info' => 'disk is removed')
);//The data used to write 
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;//format 
$eventList = $dom->createElement('EventList');//Create the root node EventList$dom->appendChild($eventList);//Add root node 
for($i = 0; $i < count($info); $i++){
 $event = $dom->createElement('event');//Create node event $text = $dom->createTextNode('PHP'.$i);//Create a text node, the value is PHP0, PHP1... $event->appendChild($text);//Add text node to node event as the value of node event 
 $attr_obj = $dom->createAttribute('obj');//Create attribute obj $attr_obj->value = $info[$i]['obj'];// Assign value to the obj attribute $event->appendChild($attr_obj);//Add the obj attribute to the event node as the attribute of the event node 
 $attr_info = $dom->createAttribute('info');
 $attr_info->value = $info[$i]['info'];
 $event->appendChild($attr_info);
 
 $eventList->appendChild($event);//Add event node to root node EventList}
 
//echo $dom->saveXML();
$dom->save('./');//Save information to the file in the current directory

The above code snippet can create an XML file and add some information to this file, including values ​​and properties. The final file is in the current directory. You can take a look at its contents.

<?xml version="1.0"?>
<EventList>
 <event obj="power" info="power is shutdown">PHP0</event>
 <event obj="memcache" info="memcache used than 90%">PHP1</event>
 <event obj="cpu" info="cpu used than 95%">PHP2</event>
 <event obj="disk" info="disk is removed">PHP3</event>
</EventList>

2. Read XML information & add new attributes

The file created in the above section is an operation object. It reads out the information in the file and adds a new attribute count to the node, with a value of 1.

/*
  * Read xml file information and add new attributes
  */
 
$dom = new DOMDocument('1.0');
$dom-&gt;load('./');//Load the file to be operated$list = $dom-&gt;getElementsByTagName('event');//Get the event node listforeach($list as $item){
 $attr_obj = $item-&gt;getAttribute('obj');//Get the value of the attribute obj $attr_info = $item-&gt;getAttribute('info');
 echo "&lt;pre&gt;Object:$attr_obj;Info:$attr_info;Value:{$item-&gt;nodeValue}&lt;/pre&gt;";
 $item-&gt;setAttribute('count',1);//Add new attribute count=1}
$dom-&gt;save('./');//Save Modify

Take a look at the extracted values:

Object:power;Info:power is shutdown;Value:PHP0
 
Object:memcache;Info:memcache used than 90%;Value:PHP1
 
Object:cpu;Info:cpu used than 95%;Value:PHP2
 
Object:disk;Info:disk is removed;Value:PHP3

Let’s look at the contents of the current file. The count attribute has been added.

<?xml version="1.0"?>
<EventList>
 <event obj="power" info="power is shutdown" count="1">PHP0</event>
 <event obj="memcache" info="memcache used than 90%" count="1">PHP1</event>
 <event obj="cpu" info="cpu used than 95%" count="1">PHP2</event>
 <event obj="disk" info="disk is removed" count="1">PHP3</event>
</EventList>

3. Modify node attributes & node values

The file in the above section is an operation object. Change the count value of the node whose obj attribute is CPU, and the new value iscount+1

/*
  * Modify the properties and values ​​of a node
  */
 
$dom = new DOMDocument('1.0');
$dom-&gt;load('./');
$list = $dom-&gt;getElementsByTagName('event');
foreach($list as $item){
 $attr_obj = $item-&gt;getAttribute('obj');
 if($attr_obj == 'cpu'){//Modify the cpu count property to make its value +1  $attr_count = $item-&gt;getAttribute('count');//Get the value of the count attribute  $item-&gt;setAttribute('count',$attr_count+1);//Reset the value of the count property  $item-&gt;nodeValue = 'Hello,Kitty';//Reset the node's value }
}
$dom-&gt;save('./');

The file after operation is as follows, to seeobj=cpuThe count property of the node has been changed and the value has been modified successfully.

<?xml version="1.0"?>
<EventList>
 <event obj="power" info="power is shutdown" count="1">PHP0</event>
 <event obj="memcache" info="memcache used than 90%" count="1">PHP1</event>
 <event obj="cpu" info="cpu used than 95%" count="2">Hello,Kitty</event>
 <event obj="disk" info="disk is removed" count="1">PHP3</event>
</EventList>

4. Delete nodes

If you want to add, you will delete it. The files in the above section are operation objects, deletedobj=disknode.

/*
  * Delete nodes
  */
 
$dom = new DOMDocument('1.0');
$dom-&gt;load('./');
$list = $dom-&gt;getElementsByTagName('event');
foreach($list as $item){
 if($item-&gt;getAttribute('obj') == 'disk'){//The node with obj=disk is used as the operation object  $item-&gt;parentNode-&gt;removeChild($item);//Delete node }
}
$dom-&gt;save('./');

Take a look at the file content after the operation. The obj=disk node has been successfully deleted.

<?xml version="1.0"?>
<EventList>
 <event obj="power" info="power is shutdown" count="1">PHP0</event>
 <event obj="memcache" info="memcache used than 90%" count="1">PHP1</event>
 <event obj="cpu" info="cpu used than 95%" count="2">Hello,Kitty</event>
 
</EventList>

Add new child nodes to the root node

The above section is an operation object, adding a new child node to the root node EventList.

/*
  * Add a child to EventList
  */
 
$dom = new DOMDocument('1.0');
$dom-&gt;load('./');
$event_list = $dom-&gt;getElementsByTagName('EventList');//Get the root node$event = $dom-&gt;createElement('event','lenovo');// Create a new node$event_list-&gt;item(0)-&gt;appendChild($event);//Add new node to root node 
$event_attr_obj = $dom-&gt;createAttribute('obj');
$event_attr_obj-&gt;value = 'lenovo';
$event-&gt;appendChild($event_attr_obj);
 
$event_attr_info = $dom-&gt;createAttribute('info');
$event_attr_info-&gt;value = 'thinkpad t430';
$event-&gt;appendChild($event_attr_info);
 
$dom-&gt;save('./');

Take a look at the file content after the operation. The new child node has been inserted into the root node.

<?xml version="1.0"?>
<EventList>
 <event obj="power" info="power is shutdown" count="1">PHP0</event>
 <event obj="memcache" info="memcache used than 90%" count="1">PHP1</event>
 <event obj="cpu" info="cpu used than 95%" count="2">Hello,Kitty</event>
 
<event obj="lenovo" info="thinkpad t430">lenovo</event></EventList>

5. About item($index)

item(index)It is a method in the DOMNodeList class, and its purpose is to return a node specified by the index. And the DOMDocument classgetElementsByTagName(name)The method returns an instance of the DOMNodeList object, so it can be called directly.item(index)method. The above section is an example, ife=dom−>getElementsByTagName(‘EventList′)Get information about the EventList node, because the EventList node is the root node, and there is only one, so when it calls item(index), only index=0 is available because it has only one; and ife=dom−>getElementsByTagName(‘event′)Get the information of the event node, because there are 4 events, so it callsitem(index)When indexing$index={0,1,2,3} , there are 4 values ​​to choose. Each node contains multiple properties, which can be expressed in an array of key-value pairs, as shown below:

object(DOMElement)#3 (18) {
 ["tagName"]=>
 string(5) "event"
 ["schemaTypeInfo"]=>
 NULL
 ["nodeName"]=>
 string(5) "event"
 ["nodeValue"]=>
 string(11) "Hello,Kitty"
 ["nodeType"]=>
 int(1)
 ["parentNode"]=>
 string(22) "(object value omitted)"
 ["childNodes"]=>
 string(22) "(object value omitted)"
 ["firstChild"]=>
 string(22) "(object value omitted)"
 ["lastChild"]=>
 string(22) "(object value omitted)"
 ["previousSibling"]=>
 string(22) "(object value omitted)"
 ["nextSibling"]=>
 string(22) "(object value omitted)"
 ["attributes"]=>
 string(22) "(object value omitted)"
 ["ownerDocument"]=>
 string(22) "(object value omitted)"
 ["namespaceURI"]=>
 NULL
 ["prefix"]=>
 string(0) ""
 ["localName"]=>
 string(5) "event"
 ["baseURI"]=>
 string(36) "file:/H:/xampp/htdocs/demo/xml/"
 ["textContent"]=>
 string(11) "Hello,Kitty"
}

It can also be used as an object's attribute, for example, to obtain the value of this node:

/*
  * About item()
  */
$dom = new DOMDocument('1.0');
$dom-&gt;load('./');
$e = $dom-&gt;getElementsByTagName('event');
echo $e-&gt;item(2)-&gt;nodeValue;
//var_dump($e-&gt;item(2));
// $e = $dom-&gt;getElementsByTagName('EventList');
// var_dump($e-&gt;item(0));
//var_dump($e-&gt;item(0)-&gt;baseURI);
// for($i=0;$i&lt;$e-&gt;length;$i++){
//  echo $e-&gt;item($i)-&gt;nodeValue;
// }

Summarize

The above is the entire content of this article. I hope the content of this article will be helpful to everyone's learning or using PHP. If you have any questions, you can leave a message to communicate.