XML Expat Parser

Expat is a stream-oriented parser. You register callback (or handler) functions with the parser and then start feeding it the document. As the parser recognizes parts of the document, it will call the appropriate handler for that part (if you've registered one). The document is fed to the parser in pieces, so you can start parsing before you have the whole document. This also allows you to parse really huge documents that won't fit into memory.
The XML Expat parser functions are part of the PHP core. There is no installation needed to use these functions.
The example below shows how to initialize the XML parser in PHP, define some handlers for different XML events, and then parse the XML file:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?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,4096))
 
  {
 
    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)));
 
  }
 
//Free the XML parser
 
xml_parser_free($parser);
 
?>
The output of the code above will be:
1
2
3
4
5
6
7
8
9
-- Note --
 
To: Tove
 
From: Jani
 
Heading: Reminder
 
Message: Don't forget me this weekend!