Question

I am trying to learn XML in php but there is something I dont understand when using namespaces.

This is my code

$xml_data = new SimpleXMLElement("<rss xmlns:g=\"http://base.google.com/ns/1.0\" version=\"2.0\"></rss>");

$make = $xml_data->addChild('channel');

$make->addChild('g:model', 'foo', 'g');
$make->addChild('g:model', 'bar', 'g');
header ("Content-Type:text/xml");
print_r($xml_data->asXML());

When looking at guides on the internet I expect to get this.

<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<g:model>foo</model>
<g:model>bar</g:model>
</channel>
</rss>

But I get this

<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<g:model xmlns:g="g">foo</model>
<g:model xmlns:g="g">bar</g:model>
</channel>
</rss>

Why do I get this extra xmlnsg:="g" and what does it do? Looking at other feeds, they dont seem to get this?

Thanks in advance!

Was it helpful?

Solution

You must omit the xmlns alias when adding the child, and provide the full xmlns in the 3rd parameter (not the alias):

$make->addChild('model', 'foo', 'http://base.google.com/ns/1.0');

You can use a technique like this to simplify / DRY up management of the namespaces

Re: What does <g:model xmlns:g="g">foo</model> do?
This overrides the previous definition of the g alias (and corrupts it in your case to g)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top