Home >php教程 >php手册 >php XMLWriter类的简单示例

php XMLWriter类的简单示例

WBOY
WBOYOriginal
2016-05-25 16:42:001000browse

前面的mysql.php 是封装的mysql数据库功能,单例模式,所以取对象是静态方法 mysql::getObject();

代码很简单,如下所示:

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

openUri('') 方法的参数可以是一个文件,那么xml数据就写入到这个文件或者 php://output 输出到缓冲区,然后 flush方法输出到页面.


本文链接:

收藏随意^^请保留教程地址.

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