An explanation of PHP native DOM object manipulation XML method

Source: Internet
Author: User
Tags baseuri lenovo
As you know, for manipulating XML type files, PHP has a built-in DOM object to handle. Operations on XML can be done from creating, adding to modifying, deleting, using the functions in the DOM object. The following article through the sample code to show you how to operate, the need for friends can refer to, let's take a look at it.

First, create

Create a new XML file, and write some data into the XML file.

/* * Create an XML file */$info = array (' obj ' = ' power ', ' info ' = ' power is shutdown '), array (' obj ' = ' memcache ', ' Info ' = ' memcache used than 90% '), array (' obj ' = ' cpu ', ' info ' = ' CPU used than '), array (' obj ' = ' disk  ' Info ' = ' disk is removed ');//data to write $dom = new DOMDocument (' 1.0 '); $dom->formatoutput = true;//formatting $eventList = $dom->createelement (' eventlist ');//Create 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 Text node, The value is PHP0,PHP1 ... $event->appendchild ($text);//Add the text node to the node event as the value of the node event $attr _obj = $dom->createattribute (' Obj ');//Create property obj $attr _obj->value = $info [$i] [' obj '];//assigns a value to the obj attribute $event->appendchild ($attr _obj);// Add the obj attribute to the event node as the property of the event node $attr _info = $dom->createattribute (' info '); $attr _info->value = $info [$i] [' info '];   $event->appendchild ($attr _info); $eventListAppendChild ($event);//Add the event node to the root node eventlist}//echo $dom->savexml (); $dom->save ('./t.xml ');// Save the information in the T.xml file in the current directory

The above code snippet can create an XML file and add some information to the file, including the values and attributes, resulting in a file that is the current directory of T.xml, and can 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>

Second, read the XML information & Add new properties

The T.xml file created in the section above is an action object that reads the information from the T.xml file and adds a new attribute count to the node with a value of 1.

/* * Read the XML file information and add a new attribute *  /$dom = new DOMDocument (' 1.0 '); $dom->load ('./t.xml ');//load the file to be manipulated $list = $dom getElementsByTagName (' event ');//Get the Event node list foreach ($list as $item) {$attr _obj = $item->getattribute (' obj ');// Gets the value of the property obj $attr _info = $item->getattribute (' info '); echo "<pre>object: $attr _obj;info: $attr _info; value:{$item->nodevalue}</pre> "; $item->setattribute (' count ', 1);//Add new attribute Count=1} $dom->save ('./t.xml ');//Save Changes

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

Look again at the contents of the current T.xml file, the Count property 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& Lt;/event></eventlist>

Third, modify node properties & node values

The T.xml file in the section above is the operand, and the Obj property is the count value of the node of the CPU, and the new value is count+1.

/* Modify the properties and values of a node */  $dom = new DOMDocument (' 1.0 '); $dom->load ('./t.xml '); $list = $dom->getelementsbytagname ( "Event"), foreach ($list as $item) {$attr _obj = $item->getattribute (' obj '), if ($attr _obj = = ' CPU ') {//Modify the CPU's Count property, Make its value +1  $attr _count = $item->getattribute (' count '),//Get the value of the Count property  $item->setattribute (' Count ', $attr _ COUNT+1);//Resets the value of the Count property  $item->nodevalue = ' hello,kitty ';//Resets the value of the node}} $dom->save ('./t.xml ');

After the operation of the T.xml file as follows, to see the OBJ=CPU node's Count property has changed, the value is also 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>

Iv. Deleting nodes

To be added, there will be deletions. The T.xml file for the above section is the action object, deleting the Obj=disk node.

/* Delete node */  $dom = new DOMDocument (' 1.0 '); $dom->load ('./t.xml '); $list = $dom->getelementsbytagname (' event ') ; foreach ($list as $item) {if ($item->getattribute (' obj ') = = ' disk ') {//Obj=disk node is the operand  $item->parentnode- >removechild ($item);//Delete node}} $dom->save ('./t.xml ');

Take a look at the contents of the T.xml file after the operation, and 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>

To add a new child node to the root node

The t.xml of the above section is the action object, adding a new child node to the root node eventlist.

/* * Add a child node to EventList */  $dom = new DOMDocument (' 1.0 '); $dom->load ('./t.xml '); $event _list = $dom getElementsByTagName (' eventlist ');//Get root node $event = $dom->createelement (' event ', ' Lenovo ');//New node $event_list- >item (0)->appendchild ($event);//Add the new node to the root node  $event _attr_obj = $dom->createattribute (' obj '); $event _ Attr_obj->value = ' Lenovo '; $event->appendchild ($event _attr_obj);  $event _attr_info = $dom->createattribute (' info '), $event _attr_info->value = ' ThinkPad t430 '; $event AppendChild ($event _attr_info);  $dom->save ('./t.xml ');

Take a look at the contents of the T.xml file after the operation, and 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>

V. About item ($INDEX)

Item (index) is a method in the Domnodelist class that is used to return a node indicated by an index. The getElementsByTagName (name) method in the DOMDocument class returns exactly one instance of the Domnodelist object, so you can call the item (index) method directly. The T.xml for the above section is an example, if E=dom−>getelementsbytagname (' eventlist′) gets the information for the EventList node because the EventList node is the root node and has only one, so it calls the item ( index), only index=0 is available because it has only 1, and if E=dom−>getelementsbytagname (' event′) Gets the information of the event node because there are 4 event, it calls the item ( Index $index={0,1,2,3}, there are 4 values to choose from. Each node contains multiple properties, which can be represented as an array of key values, as follows:

Object (DomElement) #3 {["TagName"]=> string (5) "Event" ["Schematypeinfo"]=> NULL ["NodeName"]=> string (5) "Event" ["NodeValue"]=> string (one) "Hello,kitty" ["NodeType"]=> int (1) ["ParentNode"]=> string () "(Object Value omitted) "[" ChildNodes "]=> string" (object value omitted) "[" FirstChild "]=> string ()" (Object value OMI tted) "[" LastChild "]=> string" (object value omitted) "[" PreviousSibling "]=> string ()" (object value omitted "[" nextSibling "]=> string" (object value omitted) "[" Attributes "]=> string" (object value omitted) "[" Own Erdocument "]=> string" (object value omitted) "[" NamespaceURI "]=> NULL [" prefix "]=> string (0)" "[" LocalName "]=> string (5)" Event "[" BaseURI "]=> string ()" File:/h:/xampp/htdocs/demo/xml/t.xml "[" Textcontent " ]=> string (one) "Hello,kitty"}

It can also be used as a property of an object, such as getting the value of the node:

/* for item () */$dom = new DOMDocument (' 1.0 '); $dom->load ('./t.xml '); $e = $dom->getelementsbytagname (' event '); Echo $e->item (2)->nodevalue;//var_dump ($e->item (2)),//$e = $dom->getelementsbytagname (' eventlist ');// Var_dump ($e->item (0)),//var_dump ($e->item (0)->baseuri),//for ($i =0; $i < $e->length; $i + +) {//  echo $e->item ($i)->nodevalue;//}

Summarize

The above is the entire content of this article, I hope that the content of this article for you to learn or to use PHP can be helpful


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.