Home Backend Development PHP Tutorial 用PHP与XML联手进行网站编程_PHP

用PHP与XML联手进行网站编程_PHP

Jun 01, 2016 pm 12:34 PM
parser xml programming website conduct

一、小序

  HTML简单易学又通用,一般的PHP程序就是嵌入在HTML语言之中实现的。但是随着WEB越来越广泛的应用,HTML的弱点也越来越明显了。XML的出现,弥补了这些不足,它提供了一个能够处理互联网上全部数据的通用方法。

  二、HTML的局限性分析

  1、 HTML的可扩展性差。虽然作为一般的应用,HTML应经够用了,但是在处理数学和化学等符号时,HTML有明显的缺点,而且它无法进行扩展,这样使它的发展收到了极大的限制。

  2、 链路丢失后不能自动纠正。由于Web页面的URL地址经常改变,而在改变URL地址时必须手工修改这些信息,否则就会遇到“404URL地址未找到”的信息,这大大加重了Web页面的维护工作量。

  3、 数据搜索的时间长。由于HTML主要用来对网页的显示进行控制,导致了同一个数据在不同的网页中有不同的存储格式,这样在进行数据搜索时就无法快速找到所需的资料。

  4、 HTML对双字节或者多国文字的支持不够。例如中文信息页面在不同的平台下会出现无法显示等问题。

  正是由于这些缺点,人们研究了能够代替HTML的Web页面制作语言。其中已经投入使用的有:可扩展标记语言XML、层叠样式表(CSS)以及动态HTML(DHTML)等。

  三、XML的组成

  这里简要列举几种主要的XML技术:

  1、 DTD(文档类型声明)

  DTD的主要功能是定义XML的内容模式;限制XML标记的数据范围;定义属性的数据类型。但由于它不是用XML编写的,因此扩展性比较差;而且只提供了有限的几种数据类型,因此它的作用是有限的。

  2、 XML Schema

  XML Schema的作用和DTD类似。但不同的是,Schema文件所描述的是引用它的XML文件中的元素和属性的具体类型。另外,由于它是由XML编写的,Schema和DTD相比较还有以下优点:

  ·XML Schema内容模型是开放的,可以随意扩充,而DTD无法解析扩充的内容。

  ·DTD只能把内容类型定义为一个字符串,而XML Schema允许把内容类型定义为整型、浮点型、布尔型或者许多其它的简单数据类型。

  ·XML Schema利用Namespaces将文档中特殊的节点与Schema相联系,一个XML文件可以有多个对应的Schema,而一个XML文件只能有一个DTD。

  3、 XLink

  作为一种Web语言,XML的链接能力是非常重要的。XML的链接和定址机制包括XLink、XPath和XPointer。XLink提供功能强大的链接方法,可以在文档之间建立单向或多向的复杂联结关系,还有注释链接、概要链接、扩展链接集等多种链接功能。XPath在XSLT和XPointer中使用,支持在XML文档中相对于节点和节点集的定位。XPointer在XPath的基础上提供对XML文档的内容的内部结构(如一个字符串或者选择的一个段落)的定位。XML的链接能力比HTML有了很大的增强。

  4、 CSS与XSL

  XML的一大特点就是内容与格式分离,也就是说,XML文档中并不包含如何显示/表示文档的信息。CSS与XSL(XML Style Language)解决了XML文档的显示问题。

  CSS(层叠样式表)也可以用在HTML和XML中。XSL完全使用XML的语法,功能比CSS要强大得多。

  5、 DOM

  文档对象模型(DOM)是一个与平台、语言无关的程序接口,它提供了动态访问和更新文档的内容、结构与风格的手段。可以对文当作进一步的处理,并将处理的结果更新到表示页面。

  DOM的目标就是为XML和HTML定义一个标准的编程接口,它包括核心、HTML和XML三部分。DOM的核心部分建立了一套底层的对象集,它们可以表示任何结构化的文档。HTML和XML提供了高层的接口,可以作为更方便的文档视图。DOM规范由对象和方法组成。程序员使用它们可以更容易地对特定类型的文档进行访问和操作。

  6、 Namespaces

  Namespaces是用URL加以区别的、在XML文件的元素和属性中出现的所有名称的集合。在XML中,用户可以自己定义标记和元素。因此,如果把多个XML文件合并为一个,就很可能出现冲突。Namespaces则解决了这个问题。

  四、PHP对XML的支持

  PHP对XML提供了的强大的支持。它使用了一个XML的“解析器”,并且为了支持这个解析器,它提供了20(PHP4)个XML的解析函数。下面是几个最常用的PHP解析函数。

  1. xml_parse

boolean xml_parse(int parser, string data, int [isFinal]);

  本函数用来解析 XML 格式的文件资料。参数 parser 为解析代码。参数 data 为解析的资料区块 (chunk)。参数 isFinal 可省略,若设为 true 则系统会自动送出最后的资料部分 (piece) 给 data 参数。若无错误则返回 true 值。

  2. xml_parser_create

int xml_parser_create(string [encoding]);

  本函数用来初始化一个新的 XML 解析器。参数 encoding 可省略,为 XML 使用的字符集,默认值为 ISO-8859-1,其它尚有 US-ASCII、UTF-8 二种。成功则返回 parser 代码供其它函数使用,失败则返回 false 值。

  3. xml_set_element_handler

boolean xml_set_element_handler(int parser, string startElementHandler, string endElementHandler);

  本函数配置元素的标头供 xml_parse() 函数使用。参数 parser 为解析代码。参数 startElementHandler 及 endElementHandler 分别为元素开始与结束的标头,其中的 startElementHandler 必须包括解析代码、名称、与属性,而 endElementHandler 参数包括了解析代码及名称二个参数。若无错误则返回 true 值。

  4. xml_set_character_data_handler

boolean xml_set_character_data_handler(int parser, string handler);


  本函数配置字符资料的标头。参数 parser 为解析代码。参数 handler 包括解析代码及资料字符串等二个元素。若无错误则返回 true 值。

  5. xml_get_error_code

int xml_get_error_code(int parser);

  本函数可取得 XML 在处理时的错误代码。参数 parser 为解析代码。若 parser 有错则返回 false 值,否则就返回错误代码 (如 XML_ERROR_BINARY_ENTITY_REF .... 等等)。

  6. xml_error_string

string xml_error_string(int code);

  本函数可取得 XML 在处理时的错误代码。参数 code 为解析错误代码。若无错误返回值为代码的文字描述字符串。

  7. xml_get_current_line_number

int xml_get_current_line_number(int parser);   

  本函数用来取得目前 XML 解析所正在处理的行号。参数 parser 为解析代码。若 parser 有错则返回 false 值,若无错误则返回行号数字。

  8. xml_parser_free

boolean xml_parser_free(int parser);

  本函数用来释放目前 XML 解析所使用的内存。参数 parser 为解析代码。若没有错误则返回 true 值,否则返回 false 值。


  五、案例解析

  以下是用PHP5实现读取一个以XML 1.0格式编写的通讯录address.xml,并显示其内容的示例。详解见有关注释。

<?
 //
 //第一部分:几个PHP Helper函数
 //

 /**********************************

 *从一个文件中读取XML的 *
 *内容到字符串中 *

 *********************************/

function read_file($filename)
{
 //读取文件
 $lines=file($filename);
 //变量$contents是存放文件内容的变量
 $contents="";
 while(list($key,$value)=each($lines))
 {
  $contents.=$value;
 }
 return $contents;
}

/*********************************
*当PHP遇到一个XML的起始标记时 *
*调用,其作用是按照一定的层次 *
*显示出XML的标记 *
*********************************/

function start_element($parser, $name, $attrs)
{
 //变量$depth存放标记的深度
 global $depth;
 //变量$spacer存放标记前所有的箭头符号
 $spacer="";
 for ($i=1;$i<$depth[$parser];$i++)
 {
  $spacer.="->";
 }
 //设置标记显示时的颜色
 if($depth[$parser]==0)
 {
  $font_color="red";
 }
 else
  if($depth[$parser]==1)
  {
   $font_color="green";
  }
 else
 {
  $font_color="blue";
 }
 //设置标记显示时的字体
 $font_size=5-$depth[$parser];
 if ($font_size<2)
 {
  $font_size=2;
 }
 //显示标记
 echo "<font size=".$font_size." color=".$font_color.">";
 echo $spacer.$depth[$parser];
 if ($depth[$parser]<>0)
 {
  echo "、";
 }
 echo $name."<BR>";
 echo "</font>";
 $depth[$parser]++;
 //如果是主标记就显示红色的水平线
 if($depth[$parser]==2)
 {
  echo "<hr color=red size=1>";
 }
}

/*********************************
*当PHP遇到一个XML的结束标记时 *
*调用,其作用是改变当前的层次 *
*计数,并在主标记下显示水平线 *
*********************************/

function stop_element($parser,$name)
{
 //变量$depth存放标记的深度
 global $depth;
 $depth[$parser]--;
 //如果是主标记就显示红色的水平线
 if($depth[$parser]==2)
 {
  echo "<hr color=red size=1>";
 }
}

/*********************************
*当PHP遇到一个XML的标记内容时 *
*调用,其作用是按照一定的层次 *
*显示出标记的内容 *
*********************************/

function char_data($parser,$data)
{
 //变量$depth存放标记的深度
 global $depth;
 //显示标记的内容
 $data=trim($data);
 if (strlen($data))
 {
  for ($i=1;$i<$depth[$parser]+6;$i++)
   echo " ";
   echo "<b>$data</b><br>\n";
 }
}

//
//第二部分:PHP文件开始执行处
//
//要解析的XML文件的名字

$file="address.xml";
//读取文件
$data=read_file($file);

// 产生解析器的实例
$parser = xml_parser_create();
// 设置处理函数
xml_set_element_handler($parser, "start_element", "stop_element");
xml_set_character_data_handler($parser, "char_data");
// 解析文件
if(!xml_parse($parser,$data,1))
{
 //报错
 die(sprintf("XML error: %s at line %d",
 xml_error_string(xml_get_error_code($parser)),
 xml_get_current_line_number($parser)));
}

// 释放解析器
xml_parser_free($parser);
?>

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 尊渡假赌尊渡假赌尊渡假赌

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
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
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

Unleash Your Inner Programmer: C for Absolute Beginners Unleash Your Inner Programmer: C for Absolute Beginners Oct 11, 2024 pm 03:50 PM

C is an ideal language for beginners to learn programming, and its advantages include efficiency, versatility, and portability. Learning C language requires: Installing a C compiler (such as MinGW or Cygwin) Understanding variables, data types, conditional statements and loop statements Writing the first program containing the main function and printf() function Practicing through practical cases (such as calculating averages) C language knowledge

Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Problem-Solving with Python: Unlock Powerful Solutions as a Beginner Coder Oct 11, 2024 pm 08:58 PM

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid

Collection of C++ programming puzzles: stimulate thinking and improve programming skills Collection of C++ programming puzzles: stimulate thinking and improve programming skills Jun 01, 2024 pm 10:26 PM

C++ programming puzzles cover algorithm and data structure concepts such as Fibonacci sequence, factorial, Hamming distance, maximum and minimum values ​​of arrays, etc. By solving these puzzles, you can consolidate C++ knowledge and improve algorithm understanding and programming skills.

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Python Power, Simplified: A Beginner-Friendly Approach to Programming Python Power, Simplified: A Beginner-Friendly Approach to Programming Oct 11, 2024 pm 04:53 PM

Getting Started with Python Programming Install Python: Download and install from the official website. HelloWorld!: Use print("HelloWorld!") to print the first line of code. Practical case: Calculate the area of ​​a circle: Use π (3.14159) and the radius to calculate the area of ​​the circle. Variables and data types: Use variables to store data. Data types in Python include integers, floating point numbers, strings, and Boolean values. Expressions and assignments: Use operators to connect variables, constants, and functions, and use the assignment operator (=) to assign values ​​to variables. Control flow: if-else statement: execute different code blocks based on conditions, determine odd

'Black Myth: Wukong ' Xbox version was delayed due to 'memory leak', PS5 version optimization is in progress 'Black Myth: Wukong ' Xbox version was delayed due to 'memory leak', PS5 version optimization is in progress Aug 27, 2024 pm 03:38 PM

Recently, "Black Myth: Wukong" has attracted huge attention around the world. The number of people online at the same time on each platform has reached a new high. This game has achieved great commercial success on multiple platforms. The Xbox version of "Black Myth: Wukong" has been postponed. Although "Black Myth: Wukong" has been released on PC and PS5 platforms, there has been no definite news about its Xbox version. It is understood that the official has confirmed that "Black Myth: Wukong" will be launched on the Xbox platform. However, the specific launch date has not yet been announced. It was recently reported that the Xbox version's delay was due to technical issues. According to a relevant blogger, he learned from communications with developers and "Xbox insiders" during Gamescom that the Xbox version of "Black Myth: Wukong" exists.

Demystifying C: A Clear and Simple Path for New Programmers Demystifying C: A Clear and Simple Path for New Programmers Oct 11, 2024 pm 10:47 PM

C is an ideal choice for beginners to learn system programming. It contains the following components: header files, functions and main functions. A simple C program that can print "HelloWorld" needs a header file containing the standard input/output function declaration and uses the printf function in the main function to print. C programs can be compiled and run by using the GCC compiler. After you master the basics, you can move on to topics such as data types, functions, arrays, and file handling to become a proficient C programmer.

See all articles