In accordance with the concepts that I deployed in the section you just read, it’s perfectly possible to display the results returned by the Yahoo! Web Search Service by using only a few array processing PHP functions, instead of showing monolithic chunks of XML data. To demonstrate how this process can be achieved in a simple way, below I coded another basic PHP 5 script that displays these search results by using a few (X)HTML formatting tags. The corresponding code sample is as follows: // example using Yahoo! Web Search Service - results are displayed in a basic (X)HTML format utilizing a procedural approach try{ $request='http://api.search.yahoo.com/WebSearchService/V1/webSearch? // trigger the http request if(!$results=file_get_contents($request)){ throw new Exception('Error requesting Yahoo! Web service'); } $results=unserialize($results); foreach($results[ResultSet][Result] as $result){ echo '<h2>'.$result[Title].'</h2><p>'.$result[Summary].'</p><a href="'.$result } } catch(Exception $e){ echo $e->getMessage(); exit(); } First of all, the Yahoo! Web Search Service is queried by using the same “Madonna” search term that I used earlier. And lastly, the results are returned in the form of a serialized array, since the value “php” has been assigned to the pertinent “output” parameter. Next, I simply used a “foreach” loop to iterate over the “$result” array and extract only the elements that I want to display on the browser, such as the ones whose keys are identified as “Title,” “Summary,” and “Url.” The unformatted output of the previous script can be seen below: Madonna Official site of pop diva Madonna, with news, music, media, and fan club. http://www.madonna.com/ MySpace.com - Madonna - Pop / Rock - www.myspace.com/madonna Madonna MySpace page with news, blog, music downloads, desktops, wallpapers, and more. http://www.myspace.com/madonna This is much simpler to read and code! At this point, I've provided you with an illustrative example of how to display, in a fancy format, the results returned by the Yahoo! Web Search Service. As you saw earlier, this process is very simple to grasp, so I recommend that you develop your own testing examples to extend your background in using these helpful web services with PHP 5. Final thoughts In this second article of the series, you hopefully learned the key concepts surrounding the implementation of the Yahoo! Web Search Service by using its useful “output=php” option. Indeed, when this parameter is correctly specified, displaying the corresponding search results in (X)HTML format is a matter of iterating over the elements of the pertinent output array and extracting only the ones that are relevant to your PHP application. In the next part of the series, I’m going to show you how to format search results produced by the Yahoo! Video and Image Search Services in (X)HTML, so you don’t have an excuse to miss it!
blog comments powered by Disqus |
|
|
|
|
|
|
|