views:

89

answers:

2

I am trying to generate a Google Merchant RSS Feed, using PHP's SimpleXML and DOMDocument.

The actual generating code goes like that:

$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true; 
$pRSS = $dom->createElement('rss');
$pRSS->setAttribute('version', '2.0');
$pRSS->setAttribute('xmlns:g', 'http://base.google.com/ns/1.0');
$dom->appendChild($pRSS);
$domnode = dom_import_simplexml($xml); 
$domnode = $dom->importNode($domnode, true); 
$domnode = $dom->appendChild($domnode);

$dom->save('googleproductfeed.xml');

($xml has all the data, but it's not relevant to my problem)

It all gets generated fine, but there is an XML error here:

<?xml version="1.0" encoding="utf-8"?>
<rss version="2" xmlns:g="http://base.google.com/ns/1.0"/&gt;

According to Google Merchant, Google Chrome and validome.org, there is an error in the second line. More precisely, Validome says that it should not end with />, but just >. The problem is I have no control over that. That part was generated by:

$pRSS = $dom->createElement('rss');
$pRSS->setAttribute('version', '2.0');
$pRSS->setAttribute('xmlns:g', 'http://base.google.com/ns/1.0');
+1  A: 

You should add other nodes as children to $pRSS

Emil Vikström
+1 being quicker counts :)
Pekka
+2  A: 

Shouldn't <rss> be the parent element to all the contents of the feed?

It would mean that you need to append the imported XML to $pRSS, not the parent document.

$domnode = dom_import_simplexml($xml); 
$domnode = $dom->importNode($domnode, true); 
$domnode = $pRSS->appendChild($domnode);  // Change here

Not entirely sure right now whether this won't create an extra, unnecessary node under <rss>, but it's the right direction in any case.

Pekka
You are absolutely right. There should only one outermost node in a XML document, the root node. In a RSS feed the root node is the <rss> one, in a HTML it's called <html> and so on.
Emil Vikström
ah but of course that makes sense. Thanks
nute
Although I still have one issue: `$product->addChild("g:condition", 'new');` generates `<condition>new</condition>`. It skipped the "g:".
nute
@nute that may be worth a new question - I think that has to do with Namespaces, but I don't know a solution.
Pekka
http://stackoverflow.com/questions/3018808/phps-simplexml-how-to-use-colons-in-names
nute