10

I'm using SimpleXML to create an RSS feed for Google Products and I want to create a namespaced child but when I do for example

$item->addChild('g:id', 'myid'); 

it adds

<id>myid</id> 

instead of

<g:id></g:id> 

Besides I have added at the top

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

How can I add namespaced children?

2 Answers 2

18

The namespace is the third parameter to addChild()

$item->addChild('id', 'myid', 'http://base.google.com/ns/1.0'); 

See the documentation for more information.

Sign up to request clarification or add additional context in comments.

3 Comments

it worked for me like $item->addChild('g:id', 'myid', 'http://base.google.com/ns/1.0');
Yes because I figured it out even before you posted your answer and your answer was partially helpful anyway. But I'm going to give you back the answer acceptance because of the effort. Thank you :)
php documentation says very little on this. this will generate something that looks like this: <id xmlns="base.google.com/ns/1.0">myid</id> Something I don't see in the php documentation but that I have seen in some code out there, doubling the namespace prefix seems to do the job. $item->addChild('g:g:id', 'myid'); will output <g:id>myid</g:id> Would be nice if some xml expert could confirm this is an acceptable approche.
7

Without knowing if this is an official way of doing this, I found something that did the job:

$item->addChild('g:g:id', 'myid'); 

Found this on this code http://www.sanwebe.com/2013/08/creating-rss-feed-using-php-simplexml

2 Comments

Note that this doesn't actually set the namespace for the node, though the result when serialized with SimpleXMLElement->asXML() is equivalent. Try $item->children('g', TRUE);.
5.5 years later and this workaround is still necessary. Even the approved answer can not accomplish certain results.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.