PHP native DOM Object manipulation XML

Source: Internet
Author: User
Tags baseuri lenovo
For manipulating XML type files, PHP has a built-in DOM object that can be processed. Operations on XML can be done from creating, adding to modifying, deleting, using the functions in the DOM object.

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 ' = ' Memcach E ', ' info ' = ' memcache used than 90% '), array (' obj ' = ' cpu ', ' info ' = ' CPU used than '), array (' obj ' 95% Gt ' Disk ', ' info ' = ' disk is removed ');//data to write $dom = new DOMDocument (' 1.0 '); $dom->formatoutput = true;//formatting $event List = $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 a text node with a value of PHP 0,php1. $event->appendchild ($text);//Add a text node to the node event as the value of the node event $attr _obj = $dom->createattribute (' obj '); Create the property obj $attr _obj->value = $info [$i] [' obj '];//assigns a value to the obj attribute $event->appendchild ($attr _obj);//Adds 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 the event node to the root node eventlist}//echo $dom->savexml (); $dom->save ('./t.xml ') )//Save the information to 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>

Read XML information & Add a new property


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.

/** reads the XML file information and adds 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</event></EventList>

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 so that its value is +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>

Delete a node

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 as Action object        $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 the 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>

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 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 the 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;//}

The above is the PHP native DOM object operation XML content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.