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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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 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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

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.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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.

See all articles