清单 2. Simpsons 搜索类
<?php
class Simpsons {
private $episodes = array();
public function __construct() {
$xmlDoc = new DOMDocument();
$xmlDoc->load("simpsons.xml");
foreach ($xmlDoc->documentElement->childNodes as $episode)
{
if ( $episode->nodeType == 1 ) {
$this->episodes []= array(
'episode' => $episode->getAttribute( 'episode' ),
'season' => $episode->getAttribute( 'season' ),
'title' => $episode->getAttribute( 'title' ),
'aired' => $episode->getAttribute( 'aired' ),
'summary' => $episode->nodeValue );
}
}
}
public function find( $q ) {
$found = array();
$re = "/".$q."/i";
foreach( $this->episodes as $episode ) {
if ( preg_match( $re, $episode['summary'] ) ||
preg_match( $re, $episode['title'] ) ) {
$found []= $episode;
}
}
return $found;
}
}
?>
class Simpsons {
private $episodes = array();
public function __construct() {
$xmlDoc = new DOMDocument();
$xmlDoc->load("simpsons.xml");
foreach ($xmlDoc->documentElement->childNodes as $episode)
{
if ( $episode->nodeType == 1 ) {
$this->episodes []= array(
'episode' => $episode->getAttribute( 'episode' ),
'season' => $episode->getAttribute( 'season' ),
'title' => $episode->getAttribute( 'title' ),
'aired' => $episode->getAttribute( 'aired' ),
'summary' => $episode->nodeValue );
}
}
}
public function find( $q ) {
$found = array();
$re = "/".$q."/i";
foreach( $this->episodes as $episode ) {
if ( preg_match( $re, $episode['summary'] ) ||
preg_match( $re, $episode['title'] ) ) {
$found []= $episode;
}
}
return $found;
}
}
?>
该类的构造函数使用对于 PHP 来说标准的 XML DOM 库读取剧集信息的 XML 文件。它迭代根节点的所有子节点并提取它们的季数、标题、播放日期和剧集属性,以及包含摘要的节点的文本。然后将所有数据作为一个哈希表附加到剧集数组,该数组是一个成员变量。
然后,find 函数搜索剧集列表以便使用与标题和摘要匹配的简单正则表达式来查找匹配项。任何匹配的剧集都被附加到一个数组,然后返回给调用方。如果数组为空,则没有发现匹配项。
现在有了数据,下一步就是开始构建 Ajax 响应程序,您的即时 UI 将调用该响应程序来检索数据。