Table of Contents
HTML和XML区别与联系?
一个完整的XML长什么样子?
通过DOM生成XML
用PHP解析已经存在的XML文件
用XPath来查询信息
验证XML文档是否合法
XML内容为UTF-8格式
Home php教程 php手册 PHP Cookbook读书笔记 – 第12章XML

PHP Cookbook读书笔记 – 第12章XML

Jun 06, 2016 pm 07:40 PM
php xml What notes read

什么是XML? XML(eXtensible Markup Language)是国际标准化组织的标准通用标记语言SGML的子集。由以下规范组成: 可扩展样式语言(eXtensible Sytle Language , XSL) XML链接语言(XML Linking Language,包括Xpath、Xlink和Xpointer) XML名称空间(XML N

PHP Cookbook读书笔记 – 第12章XML什么是XML?

XML(eXtensible Markup Language)是国际标准化组织的标准通用标记语言SGML的子集。由以下规范组成:

  • 可扩展样式语言(eXtensible Sytle Language , XSL)
  • XML链接语言(XML Linking Language,包括Xpath、Xlink和Xpointer)
  • XML名称空间(XML Namespace)

在PHP5之前的版本对XML的处理存在很多的问题,例如XML工具之间只具有简单的关联、每个工具不能一起协同工作等,PHP5中的新XML扩展具有下列特点:

  • 能够像一个整体一样协调工作
  • 是一个标准化的XML库:libxml2
  • 完全遵循W3C规范
  • 更有效地处理数据
  • 是你工作中合适的XML工具

HTML和XML区别与联系?

HTML和XML都是SGML的子集,所以他们有很大的相似性。下面是XML相对于HTML具有的独特性:

  • 可扩展性,用以定义需要的新标记。这对于今天的web是很有意义的
  • 结构,用于表示任意复杂程度的数据。从某种意义上说是一个小型的关系数据库
  • 校验,用以检查数据的结构正确性。通过DTD约束可以达到这一目的。
  • 媒体无关性,以多种格式发布内容。网页、手机显示的wml、其他媒体终端的显示等
  • 厂商和平台中立
  • 数据的表示与内容分离(这是与html本质区别,但现在流行的DIV+CSS设计思路与这种近似)
  • XML的元素区分大小写
  • 任何元素都需要有结束标记
  • XML只有一个根元素
  • 属性必须加上引号

一个完整的XML长什么样子?

<?xml version="1.0"?>
<shows>
    <show>
        <name>Simpsons</name>
        <channel>FOX</channel>
        <start>8:00 PM</start>
        <duration>30</duration>
    </show>
    <show>
        <name>Law & Order</name>
        <channel>NBC</channel>
        <start>8:00 PM</start>
        <duration>60</duration>
    </show>
</shows>
Copy after login

  

形式良好的XML文档须具备下列特征:

  • 每一个元素有一个开始和结束标记
  • 文档有且只有一个根元素,其他的所有元素都是它的子元素
  • 正确的格式化空元素
  • 标记的大小写匹配
  • 正确的嵌套
  • 属性值必须用引号
  • 实体在引用之前必须声明
  • 实体不能循环指向自身

通过DOM生成XML

 
// 创建一个新的文档<br>$dom = new DOMDocument('1.0');
// 创建一个根元素<book>并将其添加到文档<br>$book = $dom->appendChild($dom->createElement('book'));
// 创建一个title子元素,并添加到$book中
$title = $book->appendChild($dom->createElement('title'));
// 设置title元素的文本及cover属性
$title->appendChild($dom->createTextNode('PHP Cookbook'));
$title->setAttribute('cover', 'soft');
// 创建并将author元素添加到$book中
$sklar = $book->appendChild($dom->createElement('author'));
//添加文本到author节点<br>$sklar->appendChild($dom->createTextNode('Sklar'));

$trachtenberg = $book->appendChild($dom->createElement('author'));
$trachtenberg->appendChild($dom->createTextNode('Trachtenberg'));

// 输出完美格式化的XML文档<br>$dom->formatOutput = true;
echo $dom->saveXML();</book>
Copy after login

输出内容如下:

<?xml version="1.0"?>
<book>
  <cover>PHP Cookbook
</cover></book>
Copy after login

用PHP解析已经存在的XML文件

常用有三种方式来解析XML文件

  1. 对于简单文件采用SimpleXML
  2. 对于复杂的XML文件采用DOM扩展来实现
  3. 对于大型XML文件采用XMLReader扩展来实现

XML示例文件如下(address-book.xml):

<?xml version="1.0"?>
<address-book>
    <person id="1">
        <!--David Sklar-->
        <firstname>David</firstname>
        <lastname>Sklar</lastname>
        <city>New York</city>
        <state>NY</state>
        <email>sklar@php.net</email>
    </person>

    <person id="2">
        <!--Adam Trachtenberg-->
        <firstname>Adam</firstname>
        <lastname>Trachtenberg</lastname>
        <city>San Francisco</city>
        <state>CA</state>
        <email>amt@php.net</email>
    </person>
</address-book>
Copy after login

  

通过SimpleXML方式:

$sx = simplexml_load_file('address-book.xml');

foreach ($sx->person as $person) {
    $firstname_text_value = $person->firstname;
    $lastname_text_value = $person->lastname;

    print "$firstname_text_value $lastname_text_value\n";
}
Copy after login

通过DOM扩展:

 
$dom = new DOMDocument;
$dom->load('address-book.xml');

foreach ($dom->getElementsByTagname('person') as $person) {
    $firstname = $person->getElementsByTagname('firstname');
    $firstname_text_value = $firstname->item(0)->firstChild->nodeValue;

    $lastname = $person->getElementsByTagname('lastname');
    $lastname_text_value = $lastname->item(0)->firstChild->nodeValue;

    print "$firstname_text_value $lastname_text_value\n";
}
Copy after login

通过XMLReader扩展:

$reader = new XMLReader();
$reader->open('card-catalog.xml');

while ($reader->read()) {
    if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'author') {
        $reader->read();
        print $reader->value . "\n";
    }
}
Copy after login

用XPath来查询信息

在SimpleXML和DOM扩展中都有XPath

//SimpleXml示例
$emails = $s->xpath('/address-book/preson/email');

//DOM扩展示例
$xpath = new DOMXPath($dom);
$email = $xpath->query('/address-book/preson/email');
Copy after login

验证XML文档是否合法

在PHP中,DOM扩展支持基于DTD,XML Schema和RelaxNG的验证,而SimpleXML则只提供了XML Schema验证。

XML内容为UTF-8格式

如果数据来源为其他格式,需要经过编码为UTF-8格式,下面是通过iconv库进行转换的示例

$utf_8 = iconv('ISO-8859-1', 'UTF-8', $iso_8859_1);
Copy after login

其他参考资料:《PHP高级开发技术与实例》 清华大学出版社

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
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
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 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 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.

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: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles