Home php教程 php手册 php中对xml读取的相关函数的介绍一

php中对xml读取的相关函数的介绍一

Jun 13, 2016 pm 12:29 PM
php set xml one introduce element function object of Related parse read

对象 XML解析函数 描述 
元素 xml_set_element_handler() 元素的开始和结束 
字符数据 xml_set_character_data_handler() 字符数据的开始 
外部实体 xml_set_external_entity_ref_handler() 外部实体出现 
未解析外部实体 xml_set_unparsed_entity_decl_handler() 未解析的外部实体出现 
处理指令 xml_set_processing_instruction_handler() 处理指令的出现 
记法声明 xml_set_notation_decl_handler() 记法声明的出现 
默认 xml_set_default_handler() 其它没有指定处理函数的事件 

下面就给大家举一个小小的例子用parser函数来读取xml数据: 

xml文件代码如下: 

这个程序的结果如下:

引用: --------------------------------------------------------------------------------
名字:张三 职位:经理
名字:李四 职位:助理

复制代码 代码如下:


 
 
 
张三 
经理 
 
 
 
李四 
助理 
 
 



复制代码 代码如下:


$parser = xml_parser_create(); //创建一个parser编辑器 
xml_set_element_handler($parser, "startElement", "endElement");//设立标签触发时的相应函数 这里分别为startElement和endElenment 
xml_set_character_data_handler($parser, "characterData");//设立数据读取时的相应函数 
$xml_file="1.xml";//指定所要读取的xml文件,可以是url 
$filehandler = fopen($xml_file, "r");//打开文件 

while ($data = fread($filehandler, 4096))  

    xml_parse($parser, $data, feof($filehandler)); 
}//每次取出4096个字节进行处理 

fclose($filehandler); 
xml_parser_free($parser);//关闭和释放parser解析器 

$name=false; 
$position=false; 
function startElement($parser_instance, $element_name, $attrs)        //起始标签事件的函数 
 { 
   global $name,$position;   
   if($element_name=="NAME") 
   { 
   $name=true; 
   $position=false; 
   echo "名字:"; 
  } 
  if($element_name=="POSITION") 
   {$name=false; 
   $position=true; 
   echo "职位:"; 
  } 


function characterData($parser_instance, $xml_data)                  //读取数据时的函数  

   global $name,$position; 
   if($position) 
    echo $xml_data."
"; 
    if($name) 
     echo $xml_data."
"; 


function endElement($parser_instance, $element_name)                 //结束标签事件的函数 

 global $name,$position;  
$name=false; 
$position=false;   


?> 



PHP读取xml方法介绍

一,什么是xml,xml有什么用途
  XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized Markup Language,标准通用标记语言)。Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具。扩展标记语言XML是一种简单的数据存储语言,使用一系列简单的标记描述数据,而这些标记可以用方便的方式建立,虽然XML占用的空间比二进制数据要占用更多的空间,但XML极其简单易于掌握和使用。
  XML的用途很多,可以用来存储数据,可以用来做数据交换,为很多种应用软件提示数据等等。
二,php读取xml的方法
  xml源文件

复制代码 代码如下:





张映

28


tank

28



  1)DOMDocument读取xml

复制代码 代码如下:


$doc = new DOMDocument();
$doc->load('person.xml'); //读取xml文件
$humans = $doc->getElementsByTagName( "humans" ); //取得humans标签的对象数组
foreach( $humans as $human )
{
$names = $human->getElementsByTagName( "name" ); //取得name的标签的对象数组
$name = $names->item(0)->nodeValue; //取得node中的值,如
$sexs = $human->getElementsByTagName( "sex" );
$sex = $sexs->item(0)->nodeValue;
$olds = $human->getElementsByTagName( "old" );
$old = $olds->item(0)->nodeValue;
echo "$name - $sex - $old\n";
}
?>


  2)simplexml读取xml

复制代码 代码如下:


$xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
foreach($xml_array as $tmp){
echo $tmp->name."-".$tmp->sex."-".$tmp->old."
";
}
?>


  3)用php正则表达式来记取数据

复制代码 代码如下:


$xml = "";
$f = fopen('person.xml', 'r');
while( $data = fread( $f, 4096 ) ) {
$xml .= $data;
}
fclose( $f );
// 上面读取数据
preg_match_all( "/\(.*?)\/s", $xml, $humans ); //匹配最外层标签里面的内容
foreach( $humans[1] as $k=>$human )
{
preg_match_all( "/\(.*?)\/", $human, $name ); //匹配出名字
preg_match_all( "/\(.*?)\/", $human, $sex ); //匹配出性别
preg_match_all( "/\(.*?)\/", $human, $old ); //匹配出年龄
}
foreach($name[1] as $key=>$val){
echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
" ;
}
?>


  4)xmlreader来读取xml数据

复制代码 代码如下:


$reader = new XMLReader();
$reader->open('person.xml'); //读取xml数据
$i=1;
while ($reader->read()) { //是否读取
if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
if($i%3){
echo $reader->value; //取得node的值
}else{
echo $reader->value."
" ;
}
$i++;
}
}
?>


  三,小结
  读取xml的方法很多,简单举几个。上面四种方法都是可以把标签中的数据读出来,张映.但是他们的测重点不同,前三种方法的读取xml的function的设计重点,是为了读取标签中的值,相当于jquery中的text()方法,而xmlreader呢他就不太一样,他的重点不在读取标签中的值,而读取标签的属性,把要传送的数据,都放在属性中(不过我上面写的那个方法还是取标签中的值,因为xml文件已经给定了,我就不想在搞xml文件出来了)。
  举个例子解释一下,
  
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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles