getNamespaces()
Learn how PHP's getNamespaces() returns namespaces in scope for an XML element, with syntax, a runnable example, and how it differs from getDocNamespaces().
Introduction
SimpleXML is a PHP extension that provides a simple, object-oriented API for reading XML documents. When an XML document uses namespaces — for example <bk:title> where bk is bound to a URI — you often need to know which namespaces a given element declares or inherits. The SimpleXMLElement::getNamespaces() method answers exactly that question: it returns the namespaces that are in scope for an element. This article explains its syntax, shows a runnable example, and clarifies how it differs from the closely related getDocNamespaces().
Understanding the SimpleXMLElement::getNamespaces() function
getNamespaces() returns an associative array of the namespaces used in an element — that is, the prefixes (and the default namespace, keyed by an empty string) that actually apply to the node and, optionally, its descendants. The syntax follows the official PHP manual format:
SimpleXMLElement::getNamespaces ( bool $recursive = false ) : arrayHere, $recursive is optional. When left at its default false, the method reports only the namespaces in use on the current element. When set to true, it also walks the element's children and includes any namespaces they use. The returned array maps each prefix to its namespace URI.
It is worth contrasting two similar methods:
getNamespaces()returns the namespaces that are actually used by the element (and optionally its children).getDocNamespaces()returns every namespace declared in the document, whether or not it is used.
Example Usage
Let's look at an example to understand how SimpleXMLElement::getNamespaces() works in PHP:
In the example above, we create a SimpleXMLElement from a <book> element whose child <bk:title> uses the bk namespace bound to https://example.com/books. Passing true to getNamespaces() makes the method recurse into the children, so the bk namespace used by <bk:title> is included. We then loop over the returned array and print each prefix together with its URI. The output is:
Prefix: bk, URI: https://example.com/booksHad we called getNamespaces(false) instead, the array would be empty here, because the root <book> element itself does not use the bk prefix — only its child does.
Conclusion
The SimpleXMLElement::getNamespaces() method is a focused tool for discovering which namespaces are actually in scope for an element. Use it (with $recursive = true) when you want the namespaces an element and its children rely on, and reach for getDocNamespaces() when you need every namespace declared in the document. To learn how to query namespaced nodes once you know their prefixes, see registerXPathNamespace().