PHP Tutorial - PHP getDocNamespaces() Function






The getDocNamespaces() function returns the namespaces declared in an XML document.

Syntax

PHP getDocNamespaces() Function has the following syntax.

getDocNamespaces(recursive,from_root);

Parameter

ParameterIs requiredDescription
recursiveOptional.A Boolean value. If TRUE, all namespaces declared in parent and child nodes are returned. If FALSE, only namespaces declared in root node is returned. Default is FALSE
from_rootOptional.A Boolean value. TRUE check namespaces from the root of the XML doc. FALSE check namespaces under a child node. Default is TRUE

Return

Returns an array of namespace names with their associated URIs





Example

Return the namespaces declared in the root of the XML document:


<?php/*ww  w  . jav  a  2s.  c  o m*/
$xml=<<<XML
<?xml version="1.0" standalone="yes"?>
<books xmlns:c="http://php.net/ns">
  <c:book id="1">Java</c:book>
  <c:book id="2">PHP</c:book>
  <c:book id="3">CSS</c:book> 
</books>
XML;

$sxe=new SimpleXMLElement($xml);
$ns=$sxe->getDocNamespaces();
print_r($ns);
?>

The code above generates the following result.





Example 2

Return all namespaces declared in parent and child nodes of the XML document:


<?php/*  w w w . j a  va2s. co m*/
$xml=<<<XML
<?xml version="1.0" standalone="yes"?>
<books xmlns:c="http://php.net">
  <c:book id="1">Java</c:book>
  <c:book id="2">PHP</c:book>
  <c:book id="3" a:language="English" xmlns:a="http://php.net">CSS</c:book> 
</books>
XML;

$sxe=new SimpleXMLElement($xml);
$ns=$sxe->getDocNamespaces(TRUE);
var_dump($ns);
?>

The code above generates the following result.