A detailed approach to PHP native DOM object manipulating XML _php tips

Source: Internet
Author: User
Tags baseuri lenovo

First, create

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

* * Create XML File/* * * $info = array (' obj ' => ' power ', ' info ' => ' power is Shutdown '), array (' obj ' => ' MEMC Ache ', ' info ' => ' memcache used than 90% '), array (' obj ' => ' CPU ', ' info ' => ' CPU used than '), array (' obj ' =&G T
' Disk ', ' info ' => ' disk is removed ');//The data to be written $dom = new DOMDocument (' 1.0 '); $dom->formatoutput = true;//format $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 Section Point event $text = $dom->createtextnode (' PHP '. $i);//Create a text node with a value of PHP0,PHP1 ... $event->appendchild ($text); Adds a text node to the node event as the value of the node event $attr _obj = $dom->createattribute (' obj ');//Create attribute obj $attr _obj->value = $info [$i] [' Obj '];//assigns a value to the Obj property $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);
$eventList->appendchild ($event);//Add the event node to the root node eventlist}//echo $dom->savexml (); $dom->save ('./t.xml ');//save information to T.xml file in current directory

The code snippet above can create an XML file and add some information to the file, including values and attributes, and the resulting file is the T.xml in the current directory, and you 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" >PHP2</event>
 <event obj= "Disk" info= "disk is removed" >PHP3</event>
</EventList>

II. reading XML information & adding new attributes

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


 * * Read the XML file information and add a new attribute * * *
 
$dom = 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 ');//Get 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 property 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 at the contents of the T.xml file now, and 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" count= "1" >PHP2</event>
 <event obj= "Disk" info= "disk is Removed "count=" 1 ">PHP3</event>
</EventList>

modifying node properties & node values

The T.xml file in the above section is an action object that modifies the count value of the node that the Obj property is a CPU, and the new value is count+1 .


 * * Modify a node's properties and Values * * *
 
$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 Count property of the CPU to make it value +1
  $attr _count = $item->getattribute (' count '); Get the value
  of the Count property $item->setattribute (' count ', $attr _count+1);//Reset the value of the Count property
  $item->nodevalue = ' hello,kitty ';//Reset node's value
 }
}
$dom->save ('./t.xml ');

The T.xml file after the operation is as follows, the Count property of the node to see obj=cpu has 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" count= "2" >Hello,Kitty</event>
 <event obj= "Disk" info= " Disk is removed "count=" 1 ">PHP3</event>
</EventList>

Four, delete the node

To add, there will be deletes. The T.xml file for the above section is the action object, the deleted 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 is the object of the action
  $item-> Parentnode->removechild ($item);//delete node
 }
}
$dom->save ('./t.xml ');

Look at the contents of the T.xml file 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" count= "2" >Hello,Kitty</event>
 
</EventList>

To add a new child node to the root node

The T.xml in the above section is an action object that adds a new child node to the root node eventlist.


 * * Add a child node to the EventList *
 *
 
$dom = new DOMDocument (' 1.0 ');
$dom->load ('./t.xml ');
$event _list = $dom->getelementsbytagname (' eventlist ');//Get root node
$event = $dom->createelement (' event ', ' )//New node
$event _list->item (0)->appendchild ($event);//Add new node to 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 ');

Look at the contents of the T.xml file after the operation, and the new child nodes have 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" 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 the index. The getElementsByTagName (name) method in the DOMDocument class returns exactly the instance of a Domnodelist object, so you can call item (index) directly method. 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, There is and only one, so when it calls Item (index), the index is only index=0 available because it has only 1, and if e=dom−>getelementsbytagname (' event′) Gets the information for the event node because there are 4 event, so when it calls item , the index $index ={0,1,2,3} has 4 values to choose from. Each node contains multiple properties, which can be represented as a set of key-value arrays, 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 omitted) "
 [LastChild]]=>
 String (object value omitted)
 [previoussibling "]=>
 string" (object value omitted)
 [ NextSibling "]=>
 string" (object value omitted)
 [attributes "]=> string" (
 object value omitted) "
 [ownerdocument"]=>
 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 this node:


 * * About 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 the content of this article for everyone to learn or use PHP can help, if you have questions you can message exchange.

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.