Skip to content

Instantly share code, notes, and snippets.

Created August 6, 2010 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3f7bd7dd879ac7bf0cd8 to your computer and use it in GitHub Desktop.
Save anonymous/3f7bd7dd879ac7bf0cd8 to your computer and use it in GitHub Desktop.
<?php
class LatestSearches {
private $max = 25;
private $filename;
private $dom;
public function __construct($file) {
if(file_exists($file) && is_writable($file)) {
$this->dom = new DOMDocument();
if(!@$this->dom->load($file)) {
throw new Exception('"'.$file.'" is not a valid XML file');
} else {
$this->filename = $file;
}
} else {
throw new Exception('"'.$file.'" does not exists or is not writable.');
}
}
public function addSearch($searchString) {
$searchNode = $this->dom->createElement('search', $searchString);
$this->dom->getElementsByTagName('searches')->item(0)->appendChild($searchNode);
if($this->countEntries() > $this->max) {
$firstSearchNode = $this->dom->getElementsByTagName('search')->item(0);
$this->dom->getElementsByTagName('searches')->removeChild($firstSearchNode);
}
$this->dom->save($this->filename);
}
public function getLatestSearches($max = 25, $latestFirst = true) {
$searches = array();
$nbEntries = $this->countEntries();
$i = 0;
while($i < $nbEntries && $i < $max) {
$searches[] = $this->dom->getElementsByTagName('search')->item($i)->firstChild->nodeValue;
$i++;
}
if($latestFirst == true) {
$searches = array_reverse($searches);
}
return $searches;
}
public function countEntries() {
return $this->dom->getElementsByTagName('search')->length;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment