Enumerate registered namespaces of a PHP DOMDocument object

浪子不回头ぞ 提交于 2019-12-21 17:01:05

问题


For one of my projects, I'm using the DOMDocument class to load and manipulate XML documents.

I'd need to retrieve every namespace used in the document; however, I can't find how I'd do that. The DOMDocument class has methods to get the namespace prefix of an URI or the URI of a namespace prefix, but I've seen nothing to actually enumerate registered namespaces.

The SimpleXML library has a getNamespaces() method for that. Is there an equivalent for DOMDocument?


回答1:


DOM does not have such a function afaik. I've looked briefly at the source code of SimpleXml and I think it iterates the loaded XML and collects the namespaces (my C is very bad). The easiest solution would be to fetch the namespaces by importing the DOM dom into SimpleXml for this purpose. Maybe like this:

class DomUtils
{
    public static function getNamespaces($dom)
    {
        $sxe = simplexml_import_dom($dom);
        return $sxe->getNamespaces(); 
    }

    public static function getDocNamespaces($dom)
    {
        $sxe = simplexml_import_dom($dom);
        return $sxe->getDocNamespaces();
    }
}

You could also try to get all namespaces with XPath. See the following question and answers:

  • How to retrieve namespaces in XML files using Xpath


来源:https://stackoverflow.com/questions/2572365/enumerate-registered-namespaces-of-a-php-domdocument-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!