XML version 1.0 was introduced as a World Wide Web Consortium (W3C) specification in 1998. XML bears some resemblance to HTML; however, the main purpose of XML is to provide a way to format data that’s readable to both machines and humans. One of the reasons why XML is still widely used is because it’s easily understandable and does a stellar job at representing tree-structured data.

PHP provides a number of extensions that allow us to both consume and produce XMLdocuments. There have been a few changes introduced to many of these extensions in PHP 8. For the most part, these changes are minor; however, it’s important to be aware of these changes if we wish to be a well-rounded and informed PHP developer.

Let’s first have a look at changes to the XMLWriter extension.

Examining XMLWriter extension differences

All XMLWriter extension procedural functions now accept and return XMLWriter objects instead of resources. If we have a look at the official PHP documentation for the XMLWriter extension, however, we’ll see no references to the procedural functions. The reason for this is twofold: first, the PHP language is slowly moving away from discrete procedural functions in favor of object-oriented programming.

The second reason is that XMLWriter procedural functions are, in reality, just wrappers for XMLWriter OOP methods! As an example, xmlwriter_open_memory() is a wrapper for XMLWriter::openMemory(), xmlwriter_text() is a wrapper for XMLWriter::text(), and so forth.

If we are really set on using the XMLWriter extension using procedural programming techniques, xmlwriter_open_memory() creates an XMLWriter instance in PHP 8 rather than a resource. Likewise, all XMLWriter extension procedural functions work with XMLWriter instances rather than resources.

As with any of the extensions that now produce object instances rather than resources, a potential backwards-compatible break is possible. An example of such a break would be when we are using XMLWriter procedural functions and is_resource() to check to see if a resource has been created.

It is a best practice to use the XMLWriter extension OOP application programming interface (API) instead of the procedural API. Fortunately, the OOP API has been available since PHP 5.1. Here is a sample XML file to be used in the next example:

Get hands-on with 1200+ tech skills courses.