函式名稱:SimpleXMLElement::getDocNamespaces()
適用版本:PHP 5, PHP 7
函式描述:SimpleXMLElement::getDocNamespaces() 方法用於返回 XML 文件中定義的所有名稱空間。
用法:
array SimpleXMLElement::getDocNamespaces ( void )
引數: 該函式沒有引數。
返回值: 該函式返回一個包含名稱空間字首和名稱空間 URI 的關聯陣列。
示例:
$xml = <<<XML
<root xmlns:foo="http://www.example.com/foo" xmlns:bar="http://www.example.com/bar">
<child>Test</child>
</root>
XML;
$sxe = new SimpleXMLElement($xml);
$namespaces = $sxe->getDocNamespaces();
foreach ($namespaces as $prefix => $uri) {
echo "Prefix: $prefix, URI: $uri\n";
}
輸出:
Prefix: foo, URI: http://www.example.com/foo
Prefix: bar, URI: http://www.example.com/bar
在上面的示例中,我們首先建立一個包含名稱空間的 XML 文件。然後,我們使用 SimpleXMLElement 類將 XML 字串轉換為 SimpleXMLElement 物件。最後,我們使用 getDocNamespaces() 方法獲取文件中定義的名稱空間,並透過 foreach 迴圈遍歷輸出每個名稱空間的字首和 URI。
請注意,如果 XML 文件中沒有定義任何名稱空間,則該方法將返回一個空陣列。