DOMDocument库从标记名称中删除冒号

Let's suppose I have a HTML tag <ui:button> which refers to a button on a web page and will eventually be turned into new UIButton() in PHP.

When using the DOMDocument library, the $tagName property of the element is just button. Why is this and how can I retain ui: in it?

The ui is a namespace alias/prefix. Look for an attribute like xmlns:ui="...". The value of that attribute is an URN, a unique string defining the format the tags are part of. Often URLs are used for that purpose, because it avoids conflicts (nobody is going to use on of your domains for a namespace) and you can put documentation about the namespace on the URL. Namespaces are an XML feature that allows you to define and mix formats without conflicts between the element node names.

Let's say the attribute looks like xmlns:ui="http://example.tld/ns/ui". In this case you can read the tag name as {http://example.tld/ns/ui}button. Writing it that way would add a lot of overhead and make the XML difficult to read - hence the prefixes/aliases.

The following 3 XMLs all can be read as {http://example.tld/ns/ui}button

  • <ui:button xmlns:ui="http://example.tld/ns/ui"/>
  • <new-ui:button xmlns:new-ui="http://example.tld/ns/ui"/>
  • <button xmlns="http://example.tld/ns/ui"/>

As you can see the alias can change and is optional. If you check the properties of DOMNode you will see the properties $namespaceURI and $locaName. Build you application using them not $nodeName. Here are methods with the suffix NS that are namespace aware.