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

$_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

$_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

$_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

$_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

$_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

<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

<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

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
1254
24
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

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

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

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

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

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles