When you write enough code that communicates with third-party APIs, you’re more than likely going to find yourself communicating with an XML-based API.
And say what you will about it: Some like it, some don’t. But they exist, and they are thus going to be a necessary part of your development at some point.
If the API is well-designed, it will likely use namespaces for different types of requests and responses. And when you’re writing the client for said API, then you’re likely going to need to go about retrieving namespaced properties.
It’s easy to do it, but it’s not immediately obvious. So in this post, I’m going to walk through an example of how to do just that.
Retrieving Namespaced Properties in PHP
For this example, assume that I’m making a call to an XML-based API. To do that, I’m using the Array-To-XML library by Spatie (which is extremely convenient).
To set up the request, I create it using an array like this:
Then I’ll use the API client (which has been abstracted to keep this post as succinct as possible) to make the request from the API. From there, we can take the contents of the response and do whatever work is necessary (in this case it will be iterating through the properties of the response).
And this is where retrieving namespaces properties come into play. Assuming that we need to access a single property, or a property of a property, here’s how to do it whenever it’s namespaced:
In short, the braces serve as “variable variables” and give us access to the dynamic nature of an object.
From the manual:
Sometimes it is convenient to be able to have variable variable names. That is, a variable name which can be set and used dynamically.
And because it’s helpful to set them dynamically, it’s naturally helpful to retrieve them dynamically.
So the next time you’re working with an XML-based API (or perhaps any API), then note you can set about retrieving namespaced properties of the object via variable variables.
That makes sense, right?