I have an XML document that looks like this:
<Data
xmlns="http://www.domain.com/schema/data"
xmlns:dmd="http://www.domain.com/schema/data-metadata"
>
<Something>...</Something>
</Data>
I am parsing the information using SimpleXML in PHP. I am dealing with arrays and I seem to be having a problem with the namespace.
My question is: How do I remove those namespaces? I read the data from an XML file.
Thank you!
To remove the namespace completely, you'll need to use Regular Expressions (RegEx). For example:
Then you've stripped any xml namespaces before you load the XML (be careful with the regex through, because if you have any fields with something like:
Then it will strip the xmlns from inside the CDATA which may lead to unexpected results.
I found the answer above to be helpful, but it didn't quite work for me. This ended up working better:
If you're using XPath then it's a limitation with XPath and not PHP look at this explanation on xpath and default namespaces for more info.
More specifically its the
xmlns=""
attribute in the root node which is causing the problem. This means that you'll need to register the namespace then use a QName thereafter to refer to elements.Important: The URI used in the
registerXPathNamespace
call must be identical to the one that is used in the actual XML file.The following PHP code automatically detects the default namespace specified in the XML file under the alias "default". No all xpath queries have to be updated to include the prefix
default:
So if you want to read XML files rather they contain an default NS definition or they don't and you want to query all
Something
elements, you could use the following code: