Home  >  Article  >  Backend Development  >  PHP native DOM object manipulation XML

PHP native DOM object manipulation XML

黄舟
黄舟Original
2017-02-06 10:03:221221browse

For operating XML type files, PHP has a set of built-in DOM objects for processing. XML operations, from creation, addition to modification and deletion, can be performed using functions in the DOM object.

Create

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

/*
* 创建xml文件
*/
 
$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')
);//用来写入的数据
 
$dom = new DOMDocument('1.0');
$dom->formatOutput = true;//格式化
 
$eventList = $dom->createElement('EventList');//创建根节点EventList
$dom->appendChild($eventList);//添加根节点
 
for($i = 0; $i < count($info); $i++){
    $event = $dom->createElement('event');//创建节点event
    $text = $dom->createTextNode('PHP'.$i);//创建文本节点,值为PHP0,PHP1...
    $event->appendChild($text);//将文本节点添加到节点event,做为节点event的值
 
    $attr_obj = $dom->createAttribute('obj');//创建属性obj
    $attr_obj->value = $info[$i]['obj'];//为obj属性赋值
    $event->appendChild($attr_obj);//将obj属性添加到event节点中,做为event节点的属性
 
    $attr_info = $dom->createAttribute('info');
    $attr_info->value = $info[$i]['info'];
    $event->appendChild($attr_info);
 
    $eventList->appendChild($event);//将event节点添加到根节点EventList中
}
 
//echo $dom->saveXML();
$dom->save('./t.xml');//保存信息到当前目录下的t.xml文件中

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



  PHP0
  PHP1
  PHP2
  PHP3

Read XML information & add new attributes


The t.xml file created in the previous section is the operation object, and the t.xml is read out The information in the file and adds a new attribute count with a value of 1 to the node.

/*
* 读取xml文件信息,并添加新的属性
*/
 
$dom = new DOMDocument('1.0');
$dom->load('./t.xml');//加载要操作的文件
$list = $dom->getElementsByTagName('event');//获取event节点列表
foreach($list as $item){
    $attr_obj = $item->getAttribute('obj');//获取属性obj的值
    $attr_info = $item->getAttribute('info');
    echo "
Object:$attr_obj;Info:$attr_info;Value:{$item->nodeValue}
"; $item->setAttribute('count',1);//添加新的属性count=1 } $dom->save('./t.xml');//保存修改

Look at the extracted value:

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 content of the current t.xml file again, the count attribute has been added.



  PHP0
  PHP1
  PHP2
  PHP3

Modify node attributes & node values

The t.xml file in the above section is the operation object. Modify the count value of the node whose obj attribute is cpu. The new value is count+ 1.

/*
* 修改某一个节点的属性和值
*/
 
$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'){//修改cpu的count属性,使其值+1
        $attr_count = $item->getAttribute('count');//获取count属性的值
        $item->setAttribute('count',$attr_count+1);//重置count属性的值
        $item->nodeValue = 'Hello,Kitty';//重置节点的值
    }
}
$dom->save('./t.xml');

The t.xml file after the operation is as follows. You can see that the count attribute of the node with obj=cpu has been changed and the value has been modified successfully.



  PHP0
  PHP1
  Hello,Kitty
  PHP3

Delete node

If you want to add it, it will be deleted. The t.xml file in the above section is used as the operation object, and the node with obj=disk is deleted.

/*
* 删除节点
*/
 
$dom = new DOMDocument('1.0');
$dom->load('./t.xml');
$list = $dom->getElementsByTagName('event');
foreach($list as $item){
    if($item->getAttribute('obj') == 'disk'){//以obj=disk的节点为操作对象
        $item->parentNode->removeChild($item);//删除节点
    }
}
$dom->save('./t.xml');

Look at the contents of the t.xml file after the operation. The node with obj=disk has been successfully deleted.



  PHP0
  PHP1
  Hello,Kitty
 

Add a new child node to the root node


The t.xml in the previous section is the operation object, add a new child node to the root node EventList child nodes.

/*
* 向EventList中添加一个子节点
*/
 
$dom = new DOMDocument('1.0');
$dom->load('./t.xml');
$event_list = $dom->getElementsByTagName('EventList');//获取根节点
$event = $dom->createElement('event','lenovo');//新建节点
$event_list->item(0)->appendChild($event);//将新建节点添加到根节点中
 
$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. The new child node has been inserted into the root node.



  PHP0
  PHP1
  Hello,Kitty
 
lenovo

About item($index)

item(index) is a method in the DOMNodeList class. Its function is to return a node specified by the index. The getElementsByTagName(name) method in the DOMDocument class returns an instance of a DOMNodeList object, so the item(index) method can be called directly. Taking the t.xml in the above section as an example, if e=dom−>getElementsByTagName('EventList') gets the information of the EventList node, because the EventList node is the root node and there is only one, so when it calls item(index), The index is only available with index=0, because it only has 1; and if e=dom−>getElementsByTagName('event') gets the information of the event node, because there are 4 events, when it calls item(index), the index $ index={0,1,2,3}, there are 4 values ​​to choose from. Each node contains multiple attributes, which can be expressed in the form of 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/t.xml"
  ["textContent"]=>
  string(11) "Hello,Kitty"
}

can also be used as attributes of an object, such as getting the value of this node:

/*
* 关于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 content of PHP native DOM object operation XML. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PHP export report (case)Next article:PHP export report (case)