Home Backend Development PHP Tutorial PHP implements methods for native DOM objects to manipulate XML

PHP implements methods for native DOM objects to manipulate XML

May 31, 2018 pm 04:13 PM
php operate method

Everyone knows that for operating XML type files, PHP has a set of built-in DOM objects that can be processed. XML operations, from creation, addition to modification and deletion, can be performed using functions in the DOM object. The following article introduces how to operate through sample code. Friends in need can refer to it. Let’s take a look together.

1. Create

Create a new XML file and write some data into 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(&#39;event&#39;);//创建节点event
 $text = $dom->createTextNode(&#39;PHP&#39;.$i);//创建文本节点,值为PHP0,PHP1...
 $event->appendChild($text);//将文本节点添加到节点event,做为节点event的值
 
 $attr_obj = $dom->createAttribute(&#39;obj&#39;);//创建属性obj
 $attr_obj->value = $info[$i][&#39;obj&#39;];//为obj属性赋值
 $event->appendChild($attr_obj);//将obj属性添加到event节点中,做为event节点的属性
 
 $attr_info = $dom->createAttribute(&#39;info&#39;);
 $attr_info->value = $info[$i][&#39;info&#39;];
 $event->appendChild($attr_info);
 
 $eventList->appendChild($event);//将event节点添加到根节点EventList中
}
 
//echo $dom->saveXML();
$dom->save(&#39;./t.xml&#39;);//保存信息到当前目录下的t.xml文件中
Copy after login

The above code snippet can create an XML file and add some information to this file, including values ​​and attributes. The final file is the current directory t.xml below, 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>
Copy after login

2. Read XML information & add new attributes

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

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

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
Copy after login

Look at the content of the current t.xml file again. 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>
Copy after login

3. Modify node attributes & node values

In the above section The t.xml file is the operation object. Modify the obj attribute to be the count value of the node of cpu. The new value is count 1.

/*
 * 修改某一个节点的属性和值
 */
 
$dom = new DOMDocument(&#39;1.0&#39;);
$dom->load(&#39;./t.xml&#39;);
$list = $dom->getElementsByTagName(&#39;event&#39;);
foreach($list as $item){
 $attr_obj = $item->getAttribute(&#39;obj&#39;);
 if($attr_obj == &#39;cpu&#39;){//修改cpu的count属性,使其值+1
  $attr_count = $item->getAttribute(&#39;count&#39;);//获取count属性的值
  $item->setAttribute(&#39;count&#39;,$attr_count+1);//重置count属性的值
  $item->nodeValue = &#39;Hello,Kitty&#39;;//重置节点的值
 }
}
$dom->save(&#39;./t.xml&#39;);
Copy after login

The t.xml file after the operation is as follows. You can see that the count attribute of the node obj=cpu has changed, and the value The modification was also successful.

<?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>
Copy after login

4. Delete nodes

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

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

Look at the contents of the t.xml file after the operation. The node with obj=disk 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>
Copy after login

Add a new child node to the root node

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

/*
 * 向EventList中添加一个子节点
 */
 
$dom = new DOMDocument(&#39;1.0&#39;);
$dom->load(&#39;./t.xml&#39;);
$event_list = $dom->getElementsByTagName(&#39;EventList&#39;);//获取根节点
$event = $dom->createElement(&#39;event&#39;,&#39;lenovo&#39;);//新建节点
$event_list->item(0)->appendChild($event);//将新建节点添加到根节点中
 
$event_attr_obj = $dom->createAttribute(&#39;obj&#39;);
$event_attr_obj->value = &#39;lenovo&#39;;
$event->appendChild($event_attr_obj);
 
$event_attr_info = $dom->createAttribute(&#39;info&#39;);
$event_attr_info->value = &#39;thinkpad t430&#39;;
$event->appendChild($event_attr_info);
 
$dom->save(&#39;./t.xml&#39;);
Copy after login

Look at the contents of the t.xml file 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>
Copy after login

5. 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 it calls When item(index), only index=0 is available, because it has only 1; and ife=dom−>getElementsByTagName('event′)Get the information of the event node, because there are 4 events , so 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"
}
Copy after login

can also be used as an object Use the attributes of this node, for example, to get the value of this node:

/*
 * 关于item()
 */
$dom = new DOMDocument(&#39;1.0&#39;);
$dom->load(&#39;./t.xml&#39;);
$e = $dom->getElementsByTagName(&#39;event&#39;);
echo $e->item(2)->nodeValue;
//var_dump($e->item(2));
// $e = $dom->getElementsByTagName(&#39;EventList&#39;);
// var_dump($e->item(0));
//var_dump($e->item(0)->baseURI);
// for($i=0;$i<$e->length;$i++){
//  echo $e->item($i)->nodeValue;
// }
Copy after login

Summary: The above is the entire content of this article, I hope it can be useful for everyone’s learning help.

Related recommendations:

PHP regular matching date and time (time stamp conversion) example code

PHP implementation Example of custom image centering and cropping function [Available for testing]

Use php to obtain the example code of flv video length

The above is the detailed content of PHP implements methods for native DOM objects to manipulate XML. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles