Home  >  Article  >  Backend Development  >  Simple sample code of php XMLWriter class (RSS output)_PHP tutorial

Simple sample code of php XMLWriter class (RSS output)_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:23:551127browse

复制代码 代码如下:

include 'mysql.php';
$mysql= mysql::getObject();
$mysql->query("SELECT * FROM post");

$xml = new XMLWriter();
$xml->openUri('hello.xml'); // or 'php://output'
$xml->setIndentString(' ');
$xml->setIndent(true);
// start
$xml->startDocument('1.0', 'UTF-8');
//
$xml->startElement('rss');
$xml->writeAttribute('version','2.0');
//
$xml->startElement('channel');
// title
$xml->startElement('title');
$xml->text('title');
$xml->endElement();
// link
$xml->startElement('link');
$xml->text('http://jb51.net/post/');
$xml->endElement();
// description
$xml->startElement('description');
$xml->text('');
$xml->endElement();
// language
$xml->startElement('language');
$xml->text('zh-cn');
$xml->endElement();
// category
$xml->startElement('category');
$xml->text('IT');
$xml->endElement();
// copyright
$xml->startElement('copyright');
$xml->text('copyright 2011 jb51.net');
$xml->endElement();
// for item
while( $row = $mysql->fetch() )
{
$xml->startElement('item');
// title
$xml->startElement('title');
$xml->text( $row['title']);
$xml->endElement();
// link
$xml->startElement('link');
$xml->text( 'http://jb51.net/post/'.$row['id'].'.html');
$xml->endElement();
// description
$xml->startElement('description');
$xml->text( $row['text'] );
$xml->endElement();
// pubDate
$xml->startElement('pubDate');
$xml->text( date('D, d M Y H:i:s T', $row['time']) );
$xml->endElement();
// category tag author need to write .over
$xml->endElement(); // item
}
$xml->endElement(); // channel
$xml->endElement(); // rss
$xml->endDocument();
// $xml->flush();

前面的mysql.php 是封装的mysql数据库功能,单例模式,所以取对象是静态方法 mysql::getObject();
代码很简单
openUri('') 方法的参数可以是一个文件,那么xml数据就写入到这个文件
或者 php://output 输出到缓冲区,然后 flush方法输出到页面

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/324399.htmlTechArticle复制代码 代码如下: include 'mysql.php'; $mysql= mysql::getObject(); $mysql-query("SELECT * FROM post"); $xml = new XMLWriter(); $xml-openUri('hello.xml'); // or 'php://outp...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn