title: How to use namespaces when writing XML file with SimpleXML
body: <p>I’m writing a Google products RSS feed with SimpleXML in PHP. I’ve got my products coming from the database and creating the RSS file fine, but having problems when it comes to namespaces.</p>
  
  <p>I’ve Googled and search Stack Overflow and come across dozens of posts of how to parse XML feeds containing namespaces, but my issue is actually <em>authoring</em> an XML file with a namespace.</p>
  
  <p>Here is what the file <em>should</em> look like:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
  &lt;rss version ="2.0" xmlns:g="http://base.google.com/ns/1.0"&gt;
      &lt;!-- content --&gt;
  &lt;/rss&gt;
  </code></pre>
  
  <p>And here is my code:</p>
  
  <pre><code>&lt;?php
  
  $xml = new SimpleXMLElement('&lt;rss&gt;&lt;/rss&gt;');
  $xml-&gt;addAttribute('version', '2.0');
  
  $xml-&gt;addChild('channel');
  $xml-&gt;channel-&gt;addChild('title', 'Removed');
  $xml-&gt;channel-&gt;addChild('description', 'Removed');
  $xml-&gt;channel-&gt;addChild('link', 'Removed');
  
  foreach ($products as $product) {
      $item = $xml-&gt;channel-&gt;addChild('item');
      $item-&gt;addChild('title', htmlspecialchars($product['title']));
      $item-&gt;addChild('description', htmlspecialchars($product['title']));
      $item-&gt;addChild('link', $product['url']);
      $item-&gt;addChild('id', $product['product_id']);
      $item-&gt;addChild('price', $product['price_latest']);
      $item-&gt;addChild('brand', $product['range']);
      $item-&gt;addChild('condition', 'new');
      $item-&gt;addChild('image_link', $product['image']);
  }
  </code></pre>
  
  <p>How do I introduce the <code>g</code> namespace, both the <code>xmlns</code> declaration in the root <code>rss</code> element, and then as a prefix for <code>id</code>, <code>price</code>, <code>brand</code>, <code>condition</code> and <code>image_link</code> in each <code>item</code> element?</p>