Home Backend Development PHP Tutorial Using DOM to control XML implementation code in PHP5_PHP tutorial

Using DOM to control XML implementation code in PHP5_PHP tutorial

Jul 21, 2016 pm 03:37 PM

The following example simply demonstrates the operation of DOM on XML. For detailed explanation, please see the comments in the code

<? 
/************************************************ 
** use XML in PHP5 
** reference site: 
** http://cn.php.net/manual/zh/ref.dom.php 
** the follow codes need PHP5 support 
*************************************************/ 

//首先要创建一个DOMDocument对象 
$dom = new DomDocument(); 
//然后载入XML文件 
$dom -> load("test.xml"); 

//输出XML文件 
//header("Content-type: text/xml;charset=gb2312"); 
//echo $dom -> saveXML(); 

//保存XML文件,返回值为int(文件大小,以字节为单位) 
//$dom -> save("newfile.xml"); 

echo "<hr/>取得所有的title元素:<hr/>"; 
$titles = $dom -> getElementsByTagName("title"); 
foreach ($titles as $node){ 
echo $node -> textContent . "<br/>"; 
//这样也可以 
//echo $node->firstChild->data . "<br/>"; 
} 

/* 
echo "<hr/>从根结点遍历所有结点:<br/>"; 
foreach ($dom->documentElement->childNodes as $items) { 
//如果节点是一个元素(nodeType == 1)并且名字是item就继续循环 
if ($items->nodeType == 1 && $items->nodeName == "item") { 
foreach ($items->childNodes as $titles) { 
//如果节点是一个元素,并且名字是title就打印它. 
if ($titles->nodeType == 1 && $titles->nodeName == "title") { 
print $titles->textContent . "\n"; 
} 
} 
} 
} 
*/ 

//使用XPath查询数据 
echo "<hr/>使用XPath查询的title节点结果:<hr/>"; 
$xpath = new domxpath($dom); 
$titles = $xpath->query("/rss/channel/item/title"); 
foreach ($titles as $node){ 
echo $node->textContent."<br/>"; 
} 
/* 
这样和使用getElementsByTagName()方法差不多,但是Xpath要强大的多 
深入一点可能是这样: 
/rss/channel/item[position() = 1]/title 返回第一个item元素的所有 
/rss/channel/item/title[@id = &#39;23&#39;] 返回所有含有id属性并且值为23的title 
/rss/channel/&folder&/title 返回所有articles元素下面的title(译者注:&folder&代表目录深度) 
*/ 


//向DOM中写入新数据 
$item = $dom->createElement("item"); 
$title = $dom->createElement("title"); 
$titleText = $dom->createTextNode("title text"); 
$title->appendChild($titleText); 
$item->appendChild($title); 
$dom->documentElement->getElementsByTagName(&#39;channel&#39;)->item(0)->appendChild($item); 

//从DOM中删除节点 
//$dom->documentElement->RemoveChild($dom->documentElement->getElementsByTagName("channel")->item(0)); 
//或者使用xpath查询出节点再删除 
//$dom->documentElement->RemoveChild($xpath->query("/rss/channel")->item(0)); 
//$dom->save("newfile.xml"); 

//从DOM中修改节点数据 
//修改第一个title的文件 
//这个地方比较笨,新创建一个节点,然后替换旧的节点。如果哪位朋友有其他好的方法请一定要告诉我 
$firstTitle = $xpath->query("/rss/channel/item/title")->item(0); 
$newTitle = $dom->createElement("title"); 
$newTitle->appendChild(new DOMText("This&#39;s the new title text!!!")); 
$firstTitle->parentNode->replaceChild($newTitle, $firstTitle); 
//修改属性 
//$firstTitle = $xpath->query("/rss/channel/item/title")->item(0); 
//$firstTitle->setAttribute("orderby", "4"); 
$dom->save("newfile.xml"); 

echo "<hr/><a href=\"newfile.xml\">查看newfile.xml</a>"; 

//下面的代码获得并解析php.net的首页,将返第一个title元素的内容。 
/* 
$dom->loadHTMLFile("http://www.php.net/"); 
$title = $dom->getElementsByTagName("title"); 
print $title->item(0)->textContent; 
*/ 
?>
Copy after login

The following is the test.xml file code:

<?xml version="1.0" encoding="gb2312"?> 
<rss version="2.0"> 
<channel> 
<title>javascript</title> 
<link>http://blog.csdn.net/zhongmao/category/29515.aspx</link> 
<description>javascript</description> 
<language>zh-chs</language> 
<generator>.text version 0.958.2004.2001</generator> 
<item> 
<creator>zhongmao</creator> 
<title orderby="1">out put excel used javascript</title> 
<link>http://blog.csdn.net/zhongmao/archive/2004/09/15/105385.aspx</link> 
<pubdate>wed, 15 sep 2004 13:32:00 gmt</pubdate> 
<guid>http://blog.csdn.net/zhongmao/archive/2004/09/15/105385.aspx</guid> 
<comment>http://blog.csdn.net/zhongmao/comments/105385.aspx</comment> 
<comments>http://blog.csdn.net/zhongmao/archive/2004/09/15/105385.aspx#feedback</comments> 
<comments>2</comments> 
<commentrss>http://blog.csdn.net/zhongmao/comments/commentrss/105385.aspx</commentrss> 
<ping>http://blog.csdn.net/zhongmao/services/trackbacks/105385.aspx</ping> 
<description>test description</description> 
</item> 
<item> 
<creator>zhongmao</creator> 
<title orderby="2">out put word used javascript</title> 
<link>http://blog.csdn.net/zhongmao/archive/2004/08/06/67161.aspx</link> 
<pubdate>fri, 06 aug 2004 16:33:00 gmt</pubdate> 
<guid>http://blog.csdn.net/zhongmao/archive/2004/08/06/67161.aspx</guid> 
<comment>http://blog.csdn.net/zhongmao/comments/67161.aspx</comment> 
<comments>http://blog.csdn.net/zhongmao/archive/2004/08/06/67161.aspx#feedback</comments>
<comments>0</comments> 
<commentrss>http://blog.csdn.net/zhongmao/comments/commentrss/67161.aspx</commentrss> 
<ping>http://blog.csdn.net/zhongmao/services/trackbacks/67161.aspx</ping> 
<description>test word description</description> 
</item> 
<item> 
<creator>zhongmao</creator> 
<title orderby="3">xmlhttp</title> 
<link>http://blog.csdn.net/zhongmao/archive/2004/08/02/58417.aspx</link> 
<pubdate>mon, 02 aug 2004 10:11:00 gmt</pubdate> 
<guid>http://blog.csdn.net/zhongmao/archive/2004/08/02/58417.aspx</guid> 
<comment>http://blog.csdn.net/zhongmao/comments/58417.aspx</comment> 
<comments>http://blog.csdn.net/zhongmao/archive/2004/08/02/58417.aspx#feedback</comments>
<comments>0</comments> 
<commentrss>http://blog.csdn.net/zhongmao/comments/commentrss/58417.aspx</commentrss> 
<ping>http://blog.csdn.net/zhongmao/services/trackbacks/58417.aspx</ping> 
<description>xmlhttpaaa asd bb cc dd</description> 
</item> 
</channel> 
</rss>
Copy after login

The above is the content of using DOM to control XML implementation code in PHP5_PHP tutorial. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
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)

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

What is the difference between php5 and php8 What is the difference between php5 and php8 Sep 25, 2023 pm 01:34 PM

The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

Filtering and sorting XML data using Python Filtering and sorting XML data using Python Aug 07, 2023 pm 04:17 PM

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

Convert XML data to CSV format in Python Convert XML data to CSV format in Python Aug 11, 2023 pm 07:41 PM

Convert XML data in Python to CSV format XML (ExtensibleMarkupLanguage) is an extensible markup language commonly used for data storage and transmission. CSV (CommaSeparatedValues) is a comma-delimited text file format commonly used for data import and export. When processing data, sometimes it is necessary to convert XML data to CSV format for easy analysis and processing. Python is a powerful

Using Python to merge and deduplicate XML data Using Python to merge and deduplicate XML data Aug 07, 2023 am 11:33 AM

Using Python to merge and deduplicate XML data XML (eXtensibleMarkupLanguage) is a markup language used to store and transmit data. When processing XML data, sometimes we need to merge multiple XML files into one, or remove duplicate data. This article will introduce how to use Python to implement XML data merging and deduplication, and give corresponding code examples. 1. XML data merging When we have multiple XML files, we need to merge them

Python implements conversion between XML and JSON Python implements conversion between XML and JSON Aug 07, 2023 pm 07:10 PM

Python implements conversion between XML and JSON Introduction: In the daily development process, we often need to convert data between different formats. XML and JSON are common data exchange formats. In Python, we can use various libraries to convert between XML and JSON. This article will introduce several commonly used methods, with code examples. 1. To convert XML to JSON in Python, we can use the xml.etree.ElementTree module

Handling errors and exceptions in XML using Python Handling errors and exceptions in XML using Python Aug 08, 2023 pm 12:25 PM

Handling Errors and Exceptions in XML Using Python XML is a commonly used data format used to store and represent structured data. When we use Python to process XML, sometimes we may encounter some errors and exceptions. In this article, I will introduce how to use Python to handle errors and exceptions in XML, and provide some sample code for reference. Use try-except statement to catch XML parsing errors When we use Python to parse XML, sometimes we may encounter some

Python parsing special characters and escape sequences in XML Python parsing special characters and escape sequences in XML Aug 08, 2023 pm 12:46 PM

Python parses special characters and escape sequences in XML XML (eXtensibleMarkupLanguage) is a commonly used data exchange format used to transfer and store data between different systems. When processing XML files, you often encounter situations that contain special characters and escape sequences, which may cause parsing errors or misinterpretation of the data. Therefore, when parsing XML files using Python, we need to understand how to handle these special characters and escape sequences. 1. Special characters and

See all articles