C h a p t e r 1 0 : A P I s , R S S , a n d X M L 251 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 251 How to Use It To return the most recent photos in a public Flickr stream, just pass the Flickr account name to the plug-in, like this: $result = PIPHP_FetchFlickrStream('robinfnixon'); You can then choose how to proceed depending on the value of $result, like this: if (!$result[0]) echo 'No photos found.'; else foreach($result[1] as $photo) echo "<a href='$photo'>Photo</a> "; Or to display the images, you could use code such as this: foreach($result[1] as $photo) echo "<img Users of Flickr’s API are requested to make polling requests such as this no more than once per hour, so you are recommended to save the stream to a file or database and serve it from the cache in the future, only looking for new photos if 60 minutes has expired. The Plug-in function PIPHP_FetchFlickrStream($account) { $url = 'http://flickr.com/photos'; $rss = @file_get_contents("$url/$account/"); if (!$rss) return array(FALSE); $rss = strstr($rss, 'rss+xml'); $rss = strstr($rss, 'http://'); $rss = substr($rss, 0, strpos($rss, '"')); $xml = file_get_contents($rss); $sxml = simplexml_load_string($xml); $pics = array(); foreach($sxml->entry as $item) { for ($j=0 ; $j < sizeof($item->link) ; ++$j) { if (strstr($item->link[$j]['type'], 'image')) { $t=str_replace('_m', '', $item->link[$j]['href']); $t=str_replace('_t', '', $t); $pics[]=$t; } } } return array(count($pics), $pics); } 252 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 252 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s Get Yahoo! Answers The Yahoo! Answers web site contains questions and answers on just about any subject you can imagine, all supplied by users of the service. Sometimes this means that both the questions and the answers can be foolish or humorous, but equally they can also provide just the answer you are looking for to a problem or question you have. That makes them ideal to drop in alongside informational web pages, in much the same way as you might link to or display dictionary definitions or encyclopedia entries. Figure 10-7 shows one of the Q&As returned by this plug-in in response to a search for the term gardening. About the Plug-in This plug-in takes a search term and returns any matches for it found at Yahoo! Answers. Upon success, it returns a two-element array with the first value being the number of question/answer pairs returned, and the second an array of the Q&As, containing a sub- array in each element, with the following five values: • The subject • A Unix timestamp representing the date the question was posted • The question • The answer • A URL pointing to the original Q&A On failure, it returns a single-element array with the value FALSE. It requires this argument: • $search A search string FIGURE 10-7 With this plug-in you can add the wealth of knowledge from Yahoo! Answers to your web site. 75 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 253 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 253 Variables, Arrays, and Functions $id String containing a Yahoo! Answers API key $url String containing the API URL with the $id and $search appended $xml String containing the contents of $url $sxml SimpleXML object created from $xml $qandas Array containing the questions and answers returned $question SimpleXML object extracted from $sxml->Question $s String containing the current subject $t String containing the current timestamp $q String containing the current question $a String containing the current answer $l String containing the current link How It Works This plug-in calls the Yahoo! Answers API URL in $url, which has been preconfigured with the search query in $search (after ensuring it is suitably encoded for using in a URL by passing it through the rawurlencode() function), and a valid Yahoo! Answers API key, taken from $id. In the code provided, you will see that the API key shown is YahooDemo, and you may find that it works, although there’s no guarantee it will continue to do so. To ensure your use of this plug-in is uninterrupted, you will need to apply for a free API key of your own at http://developer.yahoo.com/wsregapp. Check the box that says Generic, No user authentication required, enter your details, and click the Continue button to be provided with your new API key. Or, if you already have any Yahoo! API keys, you can view them at http://developer.yahoo.com/wsregapp/?view. If you see generic IDs, then any of those will work. Once the API has been successfully called with the required arguments using the file_ get_contents() function (prefaced by an @ symbol to suppress any error messages if it fails), the result is returned to the string $xml. If $xml is empty or has the value FALSE, then FALSE is returned. Otherwise, the contents of $xml is converted into a SimpleXML object and placed in $sxml. An array to hold the questions and answers returned, $qandas, is also initialized. Now all the Q&As are extracted from $sxml using a foreach loop, with each element of $sxml->Question being assigned to the object $question. From there, the actual parts of each Q&A—the subject, timestamp, question, answer, and link—are retrieved and placed in the variables $s, $t, $q, $a, and $l. The link in $l is a URL pointing to the original question and answer at Yahoo! Answers, as shown in Figure 10-8. The variables $s, $q, and $a then have any HTML tag symbols such as <, >, or & replaced with their entity equivalents of <, >, &, and so on. At the same time, any \n newline characters are replaced with <br /> tags. If those strings weren’t converted to use HTML entities, then any tags posted in those fields would be treated as HTML markup, rather than displayed. We want to keep the tags viewable as sometimes they are needed to help provide HTML or other programming and web development–related answers. 254 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s 254 P l u g - i n P H P : 1 0 0 P o w e r S o l u t i o n s The five short variables are then grouped into an array and assigned to the next available element of $qandas. Once all have been processed, a two-element array is returned, the first of which is the number of Q&As returned, and the second is an array of sub-arrays, containing all the details. How to Use It Using this plug-in is as easy as ensuring you have created and set up an API key for it (as described in the previous section) and then simply calling the plug-in, passing it a search query, like this: $search = 'gardening'; $result = PIPHP_GetYahooAnswers($search); if (!$result[0]) echo "No matching questions found for $search."; An error message is displayed if $result[0] has the value FALSE. Otherwise, the returned results are all contained in sub-arrays, each within an element of $result[1], and which you could access like this for the first Q&A: $subject = $result[1][0][0]; $timestamp = $result[1][0][1]; $question = $result[1][0][2]; $answer = $result[1][0][3]; $link = $result[1][0][4]; The second Q&A is then accessible like this (and so on): $subject = $result[1][1][0]; $timestamp = $result[1][1][1]; FIGURE 10-8 The question about savvy gardening as displayed on the Yahoo! Answers web site C h a p t e r 1 0 : A P I s , R S S , a n d X M L 255 C h a p t e r 1 0 : A P I s , R S S , a n d X M L 255 $question = $result[1][1][2]; $answer = $result[1][1][3]; $link = $result[1][1][4]; However, it’s much better to use a foreach loop to iterate through all the elements of $result[1], placing each one in another variable such as $qa. From there, the various values are easily retrieved, like this: foreach($result[1] as $qa) echo "<b>$qa[0]</b> (" . date('M \'y', $qa[1]) . ')<br />'. "<b>Q.</b> <i>$qa[2]</i><br />" . "<b>A.</b> $qa[3]<br />" . "<a href='$qa[4]'>Original Question</a><br /><br />"; The only unusual thing of note here is the use of the date() function on $qa[1]. Because this value is a Unix timestamp, you can reformat it any way you like using date(). So, by passing date() the argument 'M \'y', the three-letter month abbreviation and the shorthand for the year appear next to each message. The Plug-in function PIPHP_GetYahooAnswers($search) { $search = rawurlencode($search); $id = 'YahooDemo'; // Use your own API key here $url = 'http://answers.yahooapis.com' . '/AnswersService/V1/questionSearch' . "?appid=$id&query=$search"; $xml = @file_get_contents($url); if (!$xml) return array(FALSE); $sxml = simplexml_load_string($xml); $qandas = array(); foreach($sxml->Question as $question) { $s = trim($question->Subject); $t = $question->Timestamp + 0; $q = trim($question->Content); $a = trim($question->ChosenAnswer); $l = $question->Link; $s = str_replace("\n", '<br />', htmlentities($s)); $q = str_replace("\n", '<br />', htmlentities($q)); $a = str_replace("\n", '<br />', htmlentities($a)); if (strlen($a)) $qandas[] = array($s, $t, $q, $a, $l); } return array(count($qandas), $qandas); } . timestamp $q String containing the current question $a String containing the current answer $l String containing the current link How It Works This plug- in calls the Yahoo! Answers API URL in $url,. 253 Variables, Arrays, and Functions $id String containing a Yahoo! Answers API key $url String containing the API URL with the $id and $search appended $xml String containing the contents of $url $sxml SimpleXML. $xml $qandas Array containing the questions and answers returned $question SimpleXML object extracted from $sxml->Question $s String containing the current subject $t String containing the current