PHP Function Reference

PHP SimpleXMLElement - getNamespaces() Method



The PHP SimpleXMLElement::getNamespaces() method returns namespaces used in the document.

Syntax

public SimpleXMLElement::getNamespaces(recursive)

Parameters

recursive Optional. If set to true returns all namespaces used in parent and child nodes. Otherwise, returns only namespaces used in root node.

Return Value

Returns an array of namespace names with their associated URIs.

Example:

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

<?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>+1-8054098000</phone>
  </p:user>
  
  <t:user id="Marry2015">
    <name>Marry G.</name>
    <city>London</city>
    <phone>+33-147996101</phone>
  </t:user> 
</userlist> 
XML;

$xml = new SimpleXMLElement($xmlstr);

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

The output of the above code will be:

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

❮ PHP SimpleXML Reference