getNamespaces()

Namespace are used in XML document to avoid conflict of name used by different XML developers. For example name element can have name of the student or it can have name of the fruits in basket.

We will discuss more on how to get namespace details by using PHP. Here is the example to get namespace from our XML file. We have used one more sample file which used namespace in its elements.

xml-sample2.php

<?Php
$str_xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<b:details xmlns:b="https://www.example.com/ns">
<name>Abcd</name>

<o:address xmlns:o="https://www.example.com/ns1">
  <o:door_no>234-ac</o:door_no>
  <o:street>Great Wall</o:street>
  <o:city>Alabama</o:city>
</o:address>


<r:address xmlns:r="https://www.example.com/ns2">
  <r:door_no>543-de</r:door_no>
  <r:street>Garden street</r:street>
  <r:city>New Work</r:city>
</r:address>


</b:details>
XML;
?>
We will use PHP script to get the namespaces from above XML data. Here it is
<?Php
require "xml-sample2.php";
$main1 = new SimpleXMLElement($str_xml);
$nm=$main1->getNamespaces(TRUE);
var_dump($nm);
?>
The output is
array(3) { ["b"]=> string(25) "https://www.example.com/ns" ["o"]=> string(26) "https://www.example.com/ns1" ["r"]=> string(26) "https://www.example.com/ns2" }
By using recursive to TRUE we will get name space of total documents including all child nodes. By making it FALSE it will return only root node namespaces.

Now change this line
$nm=$main1->getNamespaces(FALSE);
We will get only document root namespace
array(1) { ["b"]=> string(25) "https://www.example.com/ns" }

XML XML Children

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer