Home  >  Article  >  php教程  >  PHP XML Expat 解析器

PHP XML Expat 解析器

WBOY
WBOYOriginal
2016-06-13 09:37:34908browse

有两种基本的 XML 解析器类型:

基于树的解析器:这种解析器把 XML 文档转换为树型结构。它分析整篇文档,并提供了 API 来访问树种的元素,例如文档对象模型 (DOM)。

基于事件的解析器:将 XML 文档视为一系列的事件。当某个具体的事件发生时,解析器会调用函数来处理。

Expat 解析器是基于事件的解析器。


XML Expat 解析器是 PHP 核心的组成部分。无需安装就可以使用这些函数。


XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

初始化 XML 解析器:

<?php

//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
  {
  switch($element_name)
    {
    case "NOTE":
    echo "-- Note --<br />";
    break; 
    case "TO":
    echo "To: ";
    break; 
    case "FROM":
    echo "From: ";
    break; 
    case "HEADING":
    echo "Heading: ";
    break; 
    case "BODY":
    echo "Message: ";
    }
  }

//Function to use at the end of an element
function stop($parser,$element_name)
  {
  echo "<br />";
  }

//Function to use when finding character data
function char($parser,$data)
  {
  echo $data;
  }

//Specify element handler
xml_set_element_handler($parser,"start","stop");

//Specify data handler
xml_set_character_data_handler($parser,"char");

//Open XML file
$fp=fopen("test.xml","r");

//Read data
while ($data=fread($fp,4096))
  {
  xml_parse($parser,$data,feof($fp)) or 
  die (sprintf("XML Error: %s at line %d", 
  xml_error_string(xml_get_error_code($parser)),
  xml_get_current_line_number($parser)));
  }

//Free the XML parser
xml_parser_free($parser);

?>


Statement:
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