SoFunction
Updated on 2025-03-10

PHP Example of parsing XML file using expat

This article describes the operation of PHP using expat to parse XML file. Share it for your reference, as follows:

<?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 file:

<?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("", "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("");
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);
?>

Running results:

-- 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: Here are a few online tools for your reference:

OnlineXML/JSON mutual conversion tool:
http://tools./code/xmljson

Online formattingXML/Online compressionXML
http://tools./code/xmlformat

XMLOnline compression/formatting tools:
http://tools./code/xml_format_compress

XMLCode online formatting and beautification tools:
http://tools./code/xmlcodeformat

For more information about PHP related content, please check out the topic of this site:Summary of PHP's XML file operation skills》、《Complete collection of PHP array (Array) operation techniques》、《Summary of usage of php strings》、《PHP object-oriented programming tutorial》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope this article will be helpful to everyone's PHP programming.