8

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?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Ilian Andreev
  • 1,071
  • 3
  • 12
  • 18

2 Answers2

17

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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 1
    it worked for me like `$item->addChild('g:id', 'myid', 'http://base.google.com/ns/1.0');` – Ilian Andreev Jul 24 '11 at 20:57
  • 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 :) – Ilian Andreev Jul 25 '11 at 10:01
  • php documentation says very little on this. this will generate something that looks like this: myid 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 myid Would be nice if some xml expert could confirm this is an acceptable approche. – Antony Gibbs Jan 31 '16 at 17:58
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

Antony Gibbs
  • 1,321
  • 14
  • 24
  • 1
    Note that this doesn't actually set the namespace for the node, though the result when serialized with [`SimpleXMLElement->asXML()`](http://php.net/SimpleXMLElement.asXML) is equivalent. Try `$item->children('g', TRUE);`. – outis Sep 14 '16 at 00:57
  • 1
    5.5 years later and this workaround is still necessary. Even the approved answer can not accomplish certain results. – jiheison Jun 27 '21 at 21:41