I created an xml product feed for Google Merchant Centre some time last year. It pulls data from a sites database and formats as xml using the SimpleXML extension.
It all worked at the time, but I notice now some errors and the xml code is incorrect.
Testing locally I found the problem was the php version changing. In 5.6 it works as expected, in an 7+ the xml appears wrong.
This is an excerpt of Google’s sample data showing how the xml should look:-
<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
<title>Example - Online Store</title>
<link>http://www.example.com</link>
<description>This is a sample feed containing the required and recommended attributes for a variety of different products</description>
<!-- First example shows what attributes are required and recommended for items that are not in the apparel category -->
<item>
<!-- The following attributes are always required -->
<g:id>TV_123456</g:id>
<g:title>LG 22LB4510 - 22" LED TV - 1080p (FullHD)</g:title>
<g:description>Attractively styled and boasting stunning picture quality, the LG 22LB4510 - 22" LED TV - 1080p (FullHD) is an excellent television/monitor. The LG 22LB4510 - 22" LED TV - 1080p (FullHD) sports a widescreen 1080p panel, perfect for watching movies in their original format, whilst also providing plenty of working space for your other applications.</g:description>
<g:link>http://www.example.com/electronics/tv/22LB4510.html</g:link>
<g:image_link>http://images.example.com/TV_123456.png</g:image_link>
Note the g:
namespace on the product properties.
What I get with php7 is like:-
<item>
<g:id/>
<id>TV_123456</id>
<g:title/>
<title>LG 22LB4510 - 22" LED TV - 1080p (FullHD)</title>
Where namespaced properties have a preceding self-closing tag with the namespace, then the value inside a tag pair without namespace, which Google does not seem to like.
Any ideas how to get the expected xml format in php7?
This is a method I’m using to build the xml:-
public function makexml(){
$ns = 'http://base.google.com/ns/1.0' ; // Set namespace
$xml = new \SimpleXMLElement('<?xml version="1.0"?><rss xmlns:g="'.$ns.'" version="2.0"></rss>');
$channel = $xml->addChild('channel');
$channel->addChild('title', 'Store Name');
$channel->addChild('link', 'https://www.example.com');
foreach($this->products as $prod){ // Add each product
$prod->format();
$item = $channel->addChild('item');
foreach($prod as $prop => $value){ // Add each product property
if((!is_null($value)) && (!is_array($value))){
$item->addChild($prop, null, $ns);
$item->$prop = htmlspecialchars_decode($value);
}
}
if($prod->shipping){
foreach($prod->shipping as $ship){ // Add Shipping info
$shipopt = $item->addChild('g:shipping', null, $ns);
foreach($ship as $prop => $value){
$shipopt->addChild('g:'.$prop, $value, $ns);
}
}
}
}
return $xml ;
}