Creating a parser

resource xml_parser_create ( [string encoding])

bool xml_parser_free ( resource parser)

The first step in parsing an XML document is to create an instance of the PHP XML parser. PHP has two specific functions for the very purpose of managing instances of XML parsers: xml_parser_create() and xml_parser_free(). xml_parser_create() takes no parameters and returns a reference to an XML parser which is used in other XML functions; you should keep this reference stored in a variable for later use.

xml_parser_free() takes the parser instance you got back from xml_parser_create() and destroys it, freeing up the memory the parser was using up. PHP will, of course, clean up for you when your script ends, but it is always good house-keeping practice to clean up unused resources.

Here is an example of creating and freeing a parser, just so you are clear on how straightforward it is:

$parser = xml_parser_create();
// ... complicated XML stuff here ...

Naturally, you will need something to fill in the "complicated XML stuff here" part in between creating a parser and freeing it. Read on!


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Getting to know callback functions >>

Previous chapter: Event-based parsing

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.