Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Created January 24, 2013 10:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadaraUchiha/4620003 to your computer and use it in GitHub Desktop.
Save MadaraUchiha/4620003 to your computer and use it in GitHub Desktop.
DOMDocument code generating malformed XML.
<?php
$plantList = $this->em->getRepository('Entities\Plant')->toGoogleProductsFormat();
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput=true;
$rss = $xml->createElement('rss');
$rss->setAttribute('version', '2.0');
$rss->setAttribute('xmlns:g', 'http://base.google.com/ns/1.0');
$rss->setAttribute('xmlns:c', 'http://base.google.com/cns/1.0');
$xml->appendChild($rss);
//Create channel element
$channel = $xml->createElement('channel');
$channel = $rss->appendChild($channel);
//Loop through each plant
foreach($plantList as $plantItem){
//begin item element
$item = $xml->createElement('item');
//Loop through use key as element name and value as data
foreach ($plantItem as $key => $value)
{
//Decode HTML characters, for example '&' becomes &
//to comply with http://www.w3.org/TR/xhtml1/#C_12
$decode = htmlspecialchars_decode($value);
$decode = trim($decode);
if(empty($decode))
continue;
//Create the element
$tag = $xml->createElement($key);
$tag = $item->appendChild($tag);
//Write the field
$text = $xml->createTextNode($decode);
$text = $tag->appendChild($text);
}
$item = $channel->appendChild($item);
}
//Output xml to body
$output = $xml->SaveXML();
//Validate
$validator = new XMLValidator($xml);
$this->_response->setHeader('Content-Type', 'text/xml; charset=utf-8')->setBody($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment