Home > OS >  Getting the full name for SimpleXMLElement with namespace
Getting the full name for SimpleXMLElement with namespace

Time:06-21

When using SimpleXMLElement in PHP is there a way to get the namespace or the full name for an element that has a namespace?

For example, with the element

<namespace:name>...</namespace:name>

SimpleXMLElement::getName() only returns name and getNamespaces() returns an array of all the namespaces from the document. I would like to be able to get the specific namespace that the element uses, in this case namespace, or the full name, namespace:name.

CodePudding user response:

There doesn't appear to be a way to do this directly in SimpleXML right now. Luckily, however, you can "re-wrap" a SimpleXMLElement object as a DOMNode object using dom_import_simplexml. This doesn't re-process the XML, it just puts a different PHP object around the same internal data structure.

You can then access the information you need from the properties of the DOMNode object:

$domNode = dom_import_simplexml($simpleXmlElement);
$nsPrefix = $domNode->prefix;
$nsUri = $domNode->namespaceURI;

Bear in mind that the prefix (namespace: in your example) is entirely local to the current XML document, and even the current section of the XML document, so should not be interpreted as having permanent meaning.

The "real" namespace of the element is the namespace URI, which is the permanent identifier the local prefix has been bound to. So if you want an unambiguous representation of the element, you might use the format {http://example.com}SomeElement, i.e. '{' . $domNode->namespaceURI . '}' . $domNode->localName

  • Related