php 使用expat方式解析xml文件操作示例

yipeiwu_com5年前PHP代码库

本文实例讲述了php 使用expat方式解析xml文件操作。分享给大家供大家参考,具体如下:

test.xml:

<?xml version="1.0" encoding="UTF-8"?>
<notes>
 <note>
 <to>George</to>
 <from>John</from>
 <heading>Reminder</heading>
 <body>Don't forget the meeting!</body>
 </note>
 <note>
 <to>George2</to>
 <from>John2</from>
 <heading>Reminder2</heading>
 <body>Don't forget the meeting!2</body>
 </note>
 <instances>
 <instance st="192.168.234.121" />
 <instance st="192.168.234.28" />
 </instances>
</notes>

PHP文件:

<?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, 10)) {
// 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)));
// }
// fclose($fp);
$data = file_get_contents("test.xml");
xml_parse($parser, $data) 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);
?>

运行结果:

-- Note --
To: George
From: John
Heading: Reminder
Message: Don't forget the meeting!

-- Note --
To: George2
From: John2
Heading: Reminder2
Message: Don't forget the meeting!2

相关文章

PHP如何搭建百度Ueditor富文本编辑器

PHP如何搭建百度Ueditor富文本编辑器

本文为大家分享了PHP搭建百度Ueditor富文本编辑器的方法,供大家参考,具体内容如下 下载UEditor 官网:下载地址 将下载好的文件解压到thinkphp项目中,本文是解压到PU...

php 操作excel文件的方法小结

一、php,不用COM,生成excel文件 复制代码 代码如下: <? header("Content-type:application/vnd.ms-excel"); heade...

Mac下php 5升级到php 7的步骤详解

前言 在MAC OS X 10.11中php的版本是5.5的,近来一年多里,看到了很多关于php7介绍,以为php7增加了很多新特性,也删除了原来很多的老特性,所以一直以来并没想去尝试使...

从php核心代码分析require和include的区别

从php核心代码分析require和include的区别

深入理解PHP之require/include顺序 https://www.jb51.net/article/25867.htm普及在php手册中: require() is ide...

Thinkphp框架中D方法与M方法的区别

D()和M()方法的区别: D和M的区别主要在于 M方法不需要创建模型类文件,M方法不会读取模型类,所以默认情况下自动验证是无效的,但是可以通过动态赋值的方式实现 而D方法必须有创建模型...