<?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.
$nm=$main1->getNamespaces(FALSE);
We will get only document root namespace
array(1) { ["b"]=> string(25) "https://www.example.com/ns" }
$xml = <<<XML
<root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
XML;
$xmlObject = simplexml_load_string($xml);
$namespaces = $xmlObject->getNamespaces(true);
print_r($namespaces);
Output
Array ( [h] => http://www.w3.org/TR/html4/ [f] => http://www.w3schools.com/furniture )
$xml = <<<XML
<root xmlns:h="http://www.w3.org/TR/html4/" xmlns:f="http://www.w3schools.com/furniture">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
XML;
$xmlObject = simplexml_load_string($xml);
// Extracting namespaces
$namespaces = $xmlObject->getNamespaces(true);
print_r($namespaces);
// Register the HTML namespace for XPath queries
$xmlObject->registerXPathNamespace('h', 'http://www.w3.org/TR/html4/');
// Query for <h:td> elements
$result = $xmlObject->xpath('//h:td');
echo "HTML table data:n";
foreach ($result as $element) {
echo $element . "n"; // Output: Apples, Bananas
}
Array
(
[h] => http://www.w3.org/TR/html4/
[f] => http://www.w3schools.com/furniture
)
HTML table data:
Apples
Bananas
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.