PHP Function Reference

PHP SimpleXMLElement - getDocNamespaces() Method



The PHP SimpleXMLElement::getDocNamespaces() method returns namespaces declared in document.

Syntax

public SimpleXMLElement::getDocNamespaces(recursive, fromRoot)

Parameters

recursive Optional. If set to true returns all namespaces declared in parent and child nodes. Otherwise, returns only namespaces declared in root node. Default is false.
fromRoot Optional. If set to false, allows recursively check namespaces under a child node instead of from the root of the XML doc. Default is true.

Return Value

Returns an array of namespace names with their associated URIs.

Example: get document namespaces

The example below shows the usage of SimpleXMLElement::getDocNamespaces() method.

<?php
$xmlstr = <<<XML
<userlist xmlns:p="http://example.com/test"> 
  <p:user id="John123">
    <name>John Smith</name>
    <city>New York</city>
    <phone>+1-8054098000</phone>
  </p:user>
  
  <p:user id="Marry2015">
    <name>Marry G.</name>
    <city>London</city>
    <phone>+33-147996101</phone>
  </p:user> 
</userlist> 
XML;

$xml = new SimpleXMLElement($xmlstr);

$namespaces = $xml->getDocNamespaces();
var_dump($namespaces);
?>

The output of the above code will be:

array(1) {
  ["p"]=>
  string(24) "http://example.com/test"
}

Example: working with multiple namespaces

Consider one more example which demonstrates on working with multiple namespaces while using this function.

<?php
$xmlstr = <<<XML
<userlist xmlns:p="http://example.com/test1" xmlns:t="http://example.com/test2"> 
  <p:user id="John123">
    <name>John Smith</name>
    <city>New York</city>
    <phone xmlns:ph="http://example.com/phone">+1-8054098000</phone>
  </p:user>
  
  <t:user id="Marry2015">
    <name>Marry G.</name>
    <city>London</city>
    <phone xmlns:ph="http://example.com/phone">+33-147996101</phone>
  </t:user> 
</userlist> 
XML;

$xml = new SimpleXMLElement($xmlstr);

$namespaces = $xml->getDocNamespaces(true);
var_dump($namespaces);
?>

The output of the above code will be:

array(3) {
  ["p"]=>
  string(24) "http://example.com/test1"
  ["t"]=>
  string(24) "http://example.com/test2"
  ["ph"]=>
  string(24) "http://example.com/phone"
}

❮ PHP SimpleXML Reference