@@ -7,7 +7,6 @@ if ($proxy = str_replace("http://", "tcp://", getenv('http_proxy')))
7
7
8
8
$ quotes = new BashOrgQuotes ();
9
9
$ quote = $ quotes ->getQuote ();
10
- $ quote = $ quotes ::cleanupQuote ($ quote );
11
10
echo $ quote ."\n" ;
12
11
13
12
/**
@@ -50,7 +49,7 @@ abstract class Quotes {
50
49
* Read the cache contents
51
50
*/
52
51
function cacheRead () {
53
- $ cache = file ( $ this ->quotefile , FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES | FILE_TEXT );
52
+ $ cache = unserialize ( file_get_contents ( $ this ->quotefile ) );
54
53
if ($ cache ) {
55
54
$ this ->quotes = $ cache ;
56
55
} else {
@@ -63,7 +62,7 @@ abstract class Quotes {
63
62
* Write the cache contents to disk
64
63
*/
65
64
function cacheWrite () {
66
- if (FALSE === file_put_contents ($ this ->quotefile , implode ( "\n" , $ this ->quotes ))) {
65
+ if (FALSE === file_put_contents ($ this ->quotefile , serialize ( $ this ->quotes ))) {
67
66
throw new Exception ('Could not write quote cache ' );
68
67
}
69
68
}
@@ -87,6 +86,7 @@ abstract class Quotes {
87
86
}
88
87
return $ quote ;
89
88
}
89
+
90
90
}
91
91
92
92
/**
@@ -96,23 +96,23 @@ abstract class Quotes {
96
96
*/
97
97
class BashOrgQuotes extends Quotes {
98
98
99
- function fetchQuotes () { // */p[@class='qt']
100
- $ matches = array ();
101
- $ source = file_get_contents ("http://bash.org/?random1 " );
102
- // @todo Handle failure
103
- preg_match_all ("/<p class= \"qt \">(.+?)<\/p>/si " , $ source , $ matches );
99
+ /**
100
+ * Fetch and parse a batch of random quotes from bash.org
101
+ */
102
+ function fetchQuotes () {
103
+ libxml_use_internal_errors (TRUE );
104
+ $ doc = DOMDocument::loadHTMLFile ("http://bash.org/?random1 " );
105
+ $ xpath = new DOMXPath ($ doc );
106
+ $ elements = $ xpath ->query ('//p[@class="qt"] ' );
104
107
$ quotes = array ();
105
- foreach ($ matches [1 ] as $ match ) {
106
- $ quotes [] = str_replace ("\n" ,"" ,$ match );
108
+ foreach ($ elements as $ element ) {
109
+ $ quote = $ element ->textContent ;
110
+ $ quote = html_entity_decode ($ quote );
111
+ $ quote = str_replace ("<br /> " , "\n" , $ quote );
112
+ $ quotes [] = $ quote ;
107
113
}
108
114
return $ quotes ;
109
115
}
110
-
111
- static function cleanupQuote ($ quote ) {
112
- $ quote = html_entity_decode ($ quote );
113
- $ quote = str_replace ("<br /> " ,"\n" ,$ quote );
114
- return $ quote ;
115
- }
116
116
}
117
117
118
118
?>
0 commit comments