Home Backend Development PHP Tutorial PHP creates and parses XML 1 (36)

PHP creates and parses XML 1 (36)

Aug 08, 2016 am 09:23 AM
gt lt xml

1. Use SimpleXML to manipulate XML

To process XML files, there are two traditional processing ideas: SAX and DOM. Based on the event triggering mechanism, SAX scans the XML file once and completes the processing; DOM constructs the entire XML file into a DOM tree, and completes the processing by traversing the DOM tree. Both methods have their own advantages and disadvantages. SAX's processing ideas are relatively abstract, and DOM's processing process is relatively cumbersome, making them neither very suitable for beginners. PHP5 introduces a new set of XML processing functions, namely SimpleXML. As the name suggests, SimpleXML itself is small and compact, and only provides a few methods and functions. However, it is very powerful in processing XML files and the operation is also very simple.

 1.Create XML file

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$_xml =<<<<span>xml

</span><?xml version=<span>"</span><span>1.0</span><span>"</span> encoding=<span>"</span><span>utf-8</span><span>"</span>?>

<root>

<version><span>1.0</span></version>

<info>xml解析测试</info>

<user>

<name>张三</name>

<url>http:<span>//</span><span>www.ss.com</url></span><author sex=<span>"</span><span>男</span><span>"</span>>张三</author>

</user>

<user>

<name>宿舍</name>

<url>http:<span>//</span><span>www.ss.com</url></span><author sex=<span>"</span><span>女</span><span>"</span>>谁谁谁</author>

</user>

<user>

<name>电驴</name>

<url>http:<span>//</span><span>www.ss.com</url></span><author sex=<span>"</span><span>男</span><span>"</span>>姓黄的</author>

</user>

</root><span>xml;

$_sxe</span>= <span>new</span> SimpleXMLElement($_xml); <span>//</span><span>创建对象解析xml字符串</span>$_sxe->asXML(<span>'</span><span>test.xml</span><span>'</span>); <span>//</span><span>生成XML文件</span>

Copy after login

 2.Load XML file

1

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span>); <span>//</span><span>载入XML文件</span>var_dump($_sxe); <span>//</span><span>输出相关信息</span>print_r($_sxe); <span>//</span><span>输出主要信息</span>Reflection::export(<span>new</span> ReflectionClass($sxe)); <span>//</span><span>用反射查看详情</span>

Copy after login

 3.Parse XML file

1

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span>); <span>//</span><span>载入XML文件</span>var_dump($_sxe); <span>//</span><span>输出相关信息</span>print_r($_sxe); <span>//</span><span>输出主要信息</span>Reflection::export(<span>new</span> ReflectionClass($_sxe)); <span>//</span><span>用发射查看详情</span>echo $_sxe->asXML();<span>//</span><span>打印整个XML</span>

Copy after login

 4.Read XML data

1

2

3

4

5

6

7

8

9

10

11

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span><span>);

</span><span>//</span><span>读取一级节点的值,比如version标签</span>echo $_sxe-><span>version;

</span><span>//</span><span>如果有多个,可以设置它的数字下标</span>echo $_sxe->version[<span>2</span><span>];

</span><span>//</span><span>如果想要全部打印出来,可以用遍历</span><span>foreach</span> ($_sxe->version <span>as</span><span> $_version) {

echo </span><span>'</span><span>[</span><span>'</span>.$_version.<span>'</span><span>]</span><span>'</span><span>;

}

</span><span>//</span><span>访问二级节点的name</span>echo $_sxe->user[<span>1</span>]-><span>name;

</span><span>//</span><span>获取所有二级节点的name值</span><span>foreach</span> ($_sxe->user <span>as</span><span> $_user) {

echo </span><span>'</span><span>[</span><span>'</span>.$_user->name.<span>'</span><span>]</span><span>'</span><span>;

}

</span><span>//</span><span>获取二级节点的标签的属性</span>echo $_sxe->user[<span>1</span>]->author->attributes();

Copy after login

 5.Use XPath to get Node

1

2

3

4

5

6

7

8

9

10

11

12

$_sxe= simplexml_load_file(<span>"</span><span>test.xml</span><span>"</span><span>);

</span><span>//</span><span>使用XPath获取节点信息</span>$_version = $_sxe->xpath(<span>'</span><span>/root/version</span><span>'</span><span>);

echo $_version[</span><span>1</span><span>];

</span><span>//</span><span>遍历version</span><span>foreach</span> ($_version <span>as</span><span> $_v) {

echo </span><span>'</span><span>[</span><span>'</span>.$_v.<span>'</span><span>]</span><span>'</span><span>;

}

</span><span>//</span><span>访问二级节点</span>$_user = $_sxe->xpath(<span>'</span><span>/root/user</span><span>'</span><span>);

echo $_user[</span><span>2</span>]-><span>name;

</span><span>//</span><span>遍历二级节点</span><span>foreach</span> ($_user <span>as</span><span> $_u) {

echo </span><span>'</span><span>[</span><span>'</span>.$_u->name.<span>'</span><span>]</span><span>'</span><span>;

}

</span><span>//</span><span>访问属性</span>echo $_user[<span>1</span>]->author->attributes();

Copy after login

two. Using DOMDocument to manipulate XML

In many cases, manual generation of tags requires generating documents from top to bottom. It is necessary to ensure that the tags are complete, starting and ending tags. Although some improvements can be made with the help of some PHP functions or classes, PHP also provides a more helpful set of built-in objects and functions. The Document Object Model (DOM) provides a tree structure that makes it easy to create and process tags.

 1.DOMDocument parses XML

1

2

3

4

5

6

7

<span>//</span><span>创建一个DOMDocument()</span>$_doc = <span>new</span><span> DOMDocument();

</span><span>//</span><span>载入xml</span>$_doc->load(<span>'</span><span>test.xml</span><span>'</span><span>);

</span><span>//</span><span>取version标签</span>$_version = $_doc->getElementsByTagName(<span>'</span><span>version</span><span>'</span><span>);

echo $_version</span>->item(<span>2</span>)-><span>nodeValue;

</span><span>//</span><span>遍历version标签</span><span>foreach</span> ($_version <span>as</span><span> $v) {

echo $v</span>-><span>nodeValue;

}</span>

Copy after login

 2.DOMDocument generates XML

1

2

3

4

5

6

7

8

9

<span>//</span><span>声明xml</span>$_doc = <span>new</span> DOMDocument(<span>'</span><span>1.0</span><span>'</span>,<span>'</span><span>utf-8</span><span>'</span><span>);

</span><span>//</span><span>排版格式</span>$_doc->formatOutput = <span>true</span><span>;

</span><span>//</span><span>创建一个主标签</span>$_root = $_doc->createElement(<span>'</span><span>root</span><span>'</span><span>);

</span><span>//</span><span>创建一个一级标签version</span>$_version = $_doc->createElement(<span>'</span><span>version</span><span>'</span><span>);

</span><span>//</span><span>给version标签里赋值</span>$_versionTextNode = $_doc->createTextNode(<span>'</span><span>1.0</span><span>'</span><span>);

</span><span>//</span><span>将值放入version标签里</span>$_version-><span>appendChild($_versionTextNode);

</span><span>//</span><span>将一级标签version放入root里</span>$_root-><span>appendChild($_version);

</span><span>//</span><span>将主标签写入xml</span>$_doc-><span>appendChild($_root);

</span><span>//</span><span>生成xml</span>$_doc->save(<span>'</span><span>aaa.xml</span><span>'</span>);

Copy after login

The above introduces PHP creation and parsing XML 1 (36), including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

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

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,

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

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

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

Import XML data into database using PHP Import XML data into database using PHP Aug 07, 2023 am 09:58 AM

Importing XML data into the database using PHP Introduction: During development, we often need to import external data into the database for further processing and analysis. As a commonly used data exchange format, XML is often used to store and transmit structured data. This article will introduce how to use PHP to import XML data into a database. Step 1: Parse the XML file First, we need to parse the XML file and extract the required data. PHP provides several ways to parse XML, the most commonly used of which is using Simple

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

See all articles