views:

979

answers:

2

Hello everyone!

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!

+4  A: 

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.

$feed = simplexml_load_file('http://www.sitepoint.com/recent.rdf');
$feed->registerXPathNamespace("a", "http://www.domain.com/schema/data");
$result = $feed->xpath("a:Data/a:Something/...");
null
Right, so instead of removing... I just register the namespace. And this fixed my problem!!! You're the man! Thanks!
jchimpo
Unfortunately, this seem to be the only way.
alexeit
+1  A: 

To remove the namespace completely then you'll need to use an RegularExpression the XML string like:

$feed = file_get_contents("http://www.sitepoint.com/recent.rdf");
$feed = preg_replace("/<.*(xmlns *= *[\"'].[^\"']*[\"']).[^>]*>/i", "", $feed); // This removes ALL default namespaces.
$xml_feed = simplexml_load_string($feed);

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:

<![CDATA[ <Transfer xmlns="http://redeux.example.com"&gt;cool.&lt;/Transfer /> ]]>

Then it will strip the xmlns from inside the CDATA which may lead to unexpected results.

null