if (!($fp = fopen($this->file, "r")))
{
die("Could not read $this->file"),
}
// parse data
while ($xml = fread($fp, 4096))
{
if (!xml_parse($this->xp, $xml, feof($fp)))
{
die("XML parser error: " .
xml_error_string(xml_get_error_code($this->xp))),
}
}
// destroy parser
xml_parser_free($this->xp),
}
// opening tag handler
function elementBegin($parser, $name, $attributes)
{
$this->currentTag = $name,
// set flag if entering <channel> or <item> block
if ($name == "ITEM")
{
$this->flag = 1,
}
else if ($name == "CHANNEL")
{
$this->flag = 2,
}
}
// closing tag handler
function elementEnd($parser, $name)
{
$this->currentTag = "",
// set flag if exiting <channel> or <item> block
if ($name == "ITEM")
{
$this->count++,
$this->flag = 0,
}
else if ($name == "CHANNEL")
{
$this->flag = 0,
}
}
// character data handler
function characterData($parser, $data)
{
$data = trim(htmlspecialchars($data)),
if ($this->currentTag == "TITLE" || $this->currentTag ==
"LINK" || $this->currentTag == "DESCRIPTION")
{
// add data to $channels[] or $items[] array
if ($this->flag == 1)
{
$this->items[$this->count][strtolower($this->currentTag)] .= $data,
}
else if ($this->flag == 2)
{
// return an associative array containing channel information
// (the $channel[] array)
function getChannelInfo()
{
return $this->channel,
}
// return an associative array of arrays containing item
information
// (the $items[] array)
function getItems()
{
return $this->items,
}
}
?>
假如你对PHP类较为熟习的话,那末了解这段代码是相当轻易的。假如不太懂的话,那末请直接跳到文章末尾的链接局部,看一篇关于类任务道理的好文章。然后在回来持续浏览下面的代码。
在利用这个类之前,我要出格花几分钟指出个中的一行代码――即下面对xml_set_object()函数挪用的那一行。
如今的成绩是若何利用这个类实践生成具有多个内容来历的Web页。
<?
include("class.RDFParser.php"),
// how many items to display in each channel
$maxItems = 5,
?>
<html>
<head>
<basefont face="Verdana">
<body>
<table width="100%" border="0" cellspacing="5" cellpadding="5"> <tr>
<!-- first cell -->
<td valign=top align=left>
<font size="-1">
<?
// get and parse freshmeat.net channel
$f = new RDFParser(),
$f->setResource("http://www.freshmeat.net/backend/fm-releases.rdf"),
$f->parseResource(),
$f_channel = $f->getChannelInfo(),
$f_items = $f->getItems(),
// now format and print it...
?>
The latest from <a href=<? echo $f_channel["link"], ?>><? echo
$f_channel["title"], ?></a> <br> <ul> <? // iterate through items array
for ($x=0, $x<$maxItems, $x++) {
if (is_array($f_items[$x]))
{
// print data
$item = $f_items[$x],
echo "<li><a href=" . $item["link"] . ">" .
$item["title"] . "</a>",
}
}
?>
</ul>
</font>
</td>