Showing posts with label rss. Show all posts
Showing posts with label rss. Show all posts

Sunday, June 7, 2009

XMLWriter

the PHP5 XMLWriter class allows to easily create XML well-formed documents.

The most useful methods:
  • openURI($output) // use 'php://output' as argument to stream directly
  • startDocument('1.0') // add the initial tag. 1st argument : xml version
  • writeElement('hr') // write the empty node [hr/]
  • writeAttribute('src','img.gif') //write the attribute (inside the last node) and value
    e.g: [img src="http://www.blogger.com/img.gif" /]
  • writeElement('b','content') // write node with content "[b]content[/b]"
  • startElement('body') //add the start node [body]
  • endElement() //close the last element started. e.g: [/body]
  • How to create nodes with attributes and text:
    startElement('textarea')
    writeAttribute('name','area1')
    text('default text')
    endElement()

    output:
    [textarea name="area"]default text[/textarea]
  • endDocument()
  • flush()
  • there are other methods to write comments, DTD, CData etc... view the official documentation.
Note: I used square brackets instead of "minor or greater than" because of blogspot editor limitation.

Complete Example: RSS Feed !!

@date_default_timezone_set("GMT");
$xml = new XMLWriter();
// Output directly to the user
$xml->openURI('php://output');
$xml->startDocument('1.0');
$xml->setIndent(2);
//rss
$xml->startElement('rss');
$xml->writeAttribute('version', '2.0');
$xml->writeAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom');

//channel
$xml->startElement("channel");

//title, desc, link, date
$xml->writeElement('title', 'PHP news');
$xml->writeElement('description', 'description....');
$xml->writeElement('link', 'http://www.example.com/rss.hml');
$xml->writeElement('pubDate', date("D, d M Y H:i:s e"));

//item !
$xml->startElement("item");
$xml->writeElement('title', 'news 1');
$xml->writeElement('link', 'http://www.example.com/1.html');
$xml->writeElement('description', 'descr 1');
$xml->writeElement('pubDate', date("D, d M Y H:i:s e"));
//cat
$xml->startElement('category');
$xml->writeAttribute('domain', 'http://www.example.com/cat1.htm');
$xml->text('News');
$xml->endElement();
//end item
$xml->endElement();
//end channel
$xml->endElement();
// end rss
$xml->endElement();
//end doc
$xml->endDocument();
//flush
$xml->flush();


output:




 

PHP and tips|PHP