欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-29 20:15:34
本文实例讲述了php 使用expat方式解析xml文件操作。分享给大家供大家参考,具体如下: test.xml:

本文实例讲述了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

ps:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:

在线xml/json互相转换工具:

在线格式化xml/在线压缩xml

xml在线压缩/格式化工具:

xml代码在线格式化美化工具: