Writing an Atom feed in PHP 5

·

Another attempt at writing a PHP function for creating a basic Atom feed:

function atomise($title, $entries){  
  $feed = simplexml_load_string(
    '<feed xmlns="http://www.w3.org/2005/Atom">
      <link rel="self"/>
      <title type="html"/>
     </feed>'
    );
  $feed->title = $title;  
  $feed->link['href'] = $feed->id = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  $feed->updated = date(DATE_ATOM);
  
  $feed = dom_import_simplexml($feed);
  $dom = $feed->ownerDocument;
  
  foreach ($entries as $id => $item){
    $entry = simplexml_load_string(
      '<entry>
        <link rel="alternate" type="text/html"/>
        <title type="html"/>
        <content type="html"/>
       </entry>'
      );
      
    $entry->link['href'] = $entry->id = $id;
    $entry->title = $item['title'];
    $entry->content = $item['content'];
    
    $feed->appendChild($dom->importNode(dom_import_simplexml($entry), true));
  }
  header('Content-Type: application/atom+xml; charset=utf-8');
  print $dom->saveXML();
}

Note that the entries don't have 'updated or 'author' fields, as I can never decide what those should be for dynamic feeds.

Use it like this:

$entries = array(
  'http://example.com/1' => array(
    'title' => 'First post',
    'content' => '<p>hello</p>',
    ),
    
  'http://example.com/2' => array(
    'title' => 'Second post',
    'content' => '<p>goodbye</p>',
    ),
  );
    
atomise('Test Feed', $entries);