By Akash Mehta

Whip Up a Yahoo! Mashup Using PHP

By Akash Mehta
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

So, you want to create your own mashup? Great! Mashups — web applications that grab information from different external sources and mix it together in new and exciting ways — are fun to build, popular with users, and oh-so-very Web 2.0.

Web services, a collection of standards and data formats that enable web applications to communicate with each other and share data, are the core technology behind mashups. They allow developers to directly feed data from databases without having to resort to messy screen-scraping, and enable developers to build rich content applications that make information more useful to users.

These days, numerous companies publish public APIs for their various web services. In this article, I’ll show you how to use the powerful collection of Yahoo! APIs to build a mashup with PHP 5. First we’ll take a look at what APIs are, and the various offerings from Yahoo! that we can take advantage of. I’ll demonstrate how to search the web using Yahoo!’s entire database with only three lines of code, then take you through the process of building an entire application to search for ‘Pizza’ in ‘Palo Alto, CA’ with only 25 lines of PHP code.

This tutorial assumes a decent knowledge of PHP 5 — specifically, that you’re comfortable with the basic syntax, classes and objects, and have some basic background on web services. Take a look at the Wikipedia article on web services and SitePoint’s other PHP tutorials if you think you may have trouble with these.

The Yahoo! Developer Network

The Yahoo! Developer Network is the central reference site for all Yahoo! APIs and a way of connecting with developers and enabling them to provide Yahoo!-powered services in their applications. Check it out for more in-depth reference information.

Available APIs

A quick glance through the sidebar of the developer network homepage reveals just how many APIs Yahoo! provides. Many of the standard Yahoo! services have public APIs available, such as Search, Maps and Answers, and each API has its own set of documentation. A number of startups acquired by Yahoo! also provide APIs to their services, including, Flickr and, although each of these APIs is handled differently — check their documentation for details. Here’s a quick summary of the most popular ones.


One of the most popular APIs available from Yahoo!, the Flickr web services offer access to all the photos on Flickr, photo meta data, tags and more. Popular uses of the API include visualizing locations on maps, galleries, posters and games. You can find links to examples on the Flickr services page including Retrievr, an image search engine that allows you to search for images matching your hand-drawn sketch.

Searching for images on

Yahoo! Maps

The Yahoo! maps API is extremely powerful and allows you to create interactive maps with high quality geographic imagery, adding the power of visual location to your web application. Popular applications of the API include mapping journeys and locating users. is an excellent example of the Yahoo! Maps API, allowing you to plot your exercise routes and check your distances and other interesting statistics.

A map on

Yahoo! Search

Want to build a search function for your web site, or add related links to your web application? One of the more traditional APIs from Yahoo!, the Search API allows powerful querying of the Yahoo! web search database. Christian Langreiter offers a comparison of Yahoo and Google search results in one of his mashups.

The application compares Yahoo! and Google results

Each API has different usage restrictions, so check the relevant guidelines before you begin to develop an application. Some APIs have rate limiting — for example, the Web Search API is restricted to 5000 queries per IP address per 24 hour period. In addition, not all APIs can be used for commercial purposes. Yahoo! requires developers to register their applications with the developer network to receive an application ID, and include this application ID in each request they make to an API. While this data doesn’t affect rate limiting, it allows Yahoo! to monitor API usage and contact developers if needed. You can get an application ID — and you’ll need one to try out the sample code in this article.

Consuming the Yahoo! APIs

All the standard Yahoo! APIs are RESTful in nature; data is accessed via standard HTTP requests, where query parameters are passed to the API through the URL. What this means is that you can fetch data from the API as easily as you would fetch the HTML source of any web page, and you can test requests using any browser that will render XML. Take this sample URL:  

Try it out — visit the URL in your browser and take a look at the XML output. Since the output is XML, however, we need to parse the response XML with PHP in order to make use of it. A number of classes and XML parsing functions are readily available for PHP, but Yahoo! goes a step further: it provides an option to get all the output data in serialized form. This means that you can quickly fetch the data, run it through the unserialize function and start working with the data immediately. To get PHP serialized output, just append &output=php to the query string. Here’s a simple script that searches the web for "SitePoint" using the web search API, all in three effective lines of code:

$output = file_get_contents(  
$output = unserialize($output);  
echo '<code>'.print_r($output,TRUE).'</code>';  

Examining this snippet, we see that we first fetch the data in PHP format using the file_get_contents function, then convert it to an associative array with unserialize, before outputting a dump of the array with print_r. I should note here that to be able to use file_get_contents to open a URL requires the allow_url_fopen setting to be enabled in php.ini. Check with your host if you’re not sure if this setting is in place. Let’s take a look at the output. $output['ResultSet']['Result'] contains the data we’re looking for. Here’s a snippet of the first search result:

[Title] => SitePoint : New Articles, Fresh Thinking for Web Developers and Designers  
[Summary] => Network of sites that provice information, tools, and resources for internet-focused businesses and web developers, including,, and  
[Url] =>

Compare this with the first result for the term "SitePoint" on the official Yahoo! Search site and you’ll see it’s the same.

Result for a search on

All the data you would normally get through a Yahoo! search is available through the API! Forget messy screen scraping — Yahoo! makes it easy to get the search results directly. With another few lines of code, we can turn our array into a full search results page. You can probably already see how to make a search engine with the Yahoo! web search API here — it’s that simple! Building your own search engine from scratch would usually involve buying a data centre and spending years spidering the web, but Yahoo! provides all the data free of charge (with usage restrictions, of course). You may have heard of, a site that lets you create your search engine. Well, Rollyo is built using the Yahoo! APIs. With just a few lines of PHP, we can query the Yahoo! web search API, parse the API output, extract the data, format it and output it — that’s a lot of power to have available at your fingertips.

Most of the Yahoo! APIs are just as easy to use as Web Search, and Yahoo! provides a guide to constructing REST queries if you need further information about fetching data from the APIs. Each API method has a documentation page outlining the parameters available, return values, possible output formats (XML, PHP, etc.) and potential errors. It should be noted that all parameters are URL encoded, so php code should become php+code, or the API may return unexpected output. PHP’s inbuilt urlencode function is sufficient for this task. As a general guide, each service has a base URL something like the following:

Each service requires certain parameters, one of which will be your application ID, and most services will have a query parameter. In the previous example search, we use the parameters appid, query, results and output. In this case, appid is the application ID, query is what we are searching for ("SitePoint") and output is the format we want the API output in (php for serialized PHP form, optional). The results parameter is optional, however I use it here to limit the output to two search results in order to reduce server load. If you don’t need the standard 10 results, limiting the output through the results parameter is highly advisable. We append a question mark and the parameters to the URI, separating each parameter with an ampersand (&) and using the standard option=value format, just like any other HTTP request.

So now that you’ve had a gentle introduction to the usage of Yahoo! APIs, how they behave and what they provide access to, let’s take things up a notch and look at how we can actually put these APIs to good use.

PHP 5 and the Yahoo! APIs

PHP 5 has a number of features that help us make effective use of the Yahoo! APIs. PHP 5’s improved internal OOP support enables developers to efficiently build applications, and we can take advantage of this by using classes to rapidly develop libraries that make use of the Yahoo! APIs. The introduction of the file_get_contents function allows easy querying of the APIs, and as I mentioned before, PHP has the added advantage of receiving serialized output from most of the APIs with inbuilt parsing functions. Even though the HTTP extension is available in PHP 5, we won’t need it for low-end API consumption. PHP 5 developers can easily query the APIs, parse the output, deal with errors and make use of the data without too much trouble.

Quick and Easy Mashups

To demonstrate the power of the Yahoo! APIs, we’re going to put together a very simple, practical application using PHP 5 and various Yahoo! APIs. What we want to do is query the local search API for data from Yahoo! Local, where users discuss and rate local attractions, businesses and so on. Then we’ll place that data on a map, showing geographically where those attractions are located.

YahooAPI Client Class in PHP 5

To make our lives easier, we’re going to use a PHP class that helps us to query the Yahoo! APIs. The base class needs to have the following functionality:

  • Set the web service to be used.
  • Add parameters to the request.
  • Execute the call to the remote API.
  • Fetch the output.

I’ve built a very simple, extensible class to do just this, called YahooAPI — take a look in the code archive for this article. While I won’t go into the details of the YahooAPI class, using it is very easy. In the previous example we searched for "SitePoint" on the Web. The same task can be achieved very easily with the class:

$api = new YahooAPI();  
$output = $api->doAPICall();

This is exactly the same as the previous search example, except that now we use the client class. In this case, using the class is more verbose, but with more complex and repeated calls to the API, using the class can save time and simplify maintenance.

Manipulating Data from API Calls

Now that we have everything we need to get to work, I’ll show you how to easily manipulate data from the Yahoo! APIs.

Let’s use our new YahooAPI class to search for ‘Pizza’ in ‘Palo Alto, CA’ using the Local Search API. Take a look at the documentation page for the latest version of the local search API. This is the base URL for the service:  

So we’ll call the setService method of the YahooAPI class and give it the base URL. Looking through the request parameters in the documentation, we’ll need to submit the 'appid', 'query' and 'location' parameters. After we set the required application ID, we then need to choose a location — we’ll use a city and state for now — and a query. Let’s say we’re searching for ‘Pizza’ in ‘Palo Alto, CA’. In simple, procedural PHP code using the YahooAPI class, the search would look something like this:

$api = new YahooAPI();  
$api->setParam('location','Palo Alto, CA');  
$output = $api->doAPICall();

The call to the API here is the same as fetching  

through any method, so take a look at that URL in your web browser. Clearly the information we’re looking for is within each <Result> node, and all <Result> nodes are within one big <ResultSet> node. The PHP version that we’re fetching has exactly the same structure as the XML, except that it’s in an easily usable array. After fetching all that data into the $output variable, all we have to do is iterate over the $output['ResultSet']['Result'] elements and fetch the data we need. Try it out — add the following code after the previous example and run it on your web server:

foreach($output['ResultSet']['Result'] as $result) {  
 echo $result['Title'].'<br/>';  

You should receive something like the following output:

Patxi's Chicago Pizza  
Papa Murphys Pizza Take & Bake  
New York Pizza  
Round Table Pizza Palo Alto  
Domino's Pizza  
California Pizza Kitchen  
Pizza My Heart  
Ramonas Pizza  
Round Table Pizza Palo Alto  
Spot A Pizza

LocalSearch Client Class in PHP 5

Now let’s extend the YahooAPI class to query the Yahoo! Local Search API. We can easily create a class that manages all this work for us. Instead of the previous procedural code, if we extend the YahooAPI class and create some appropriately-named methods — for example locationSearch($query, $location) — we can further simplify the process of interacting with the APIs.

I’ve written an example class that generally covers everything we need for interacting with the Local Search API. It has three main methods: locationSearch, positionSearch and extractResults. Here’s the code:

class LocalSearch extends YahooAPI  

The constructor method sets the basic properties we’ll always need for each Local Search API request:

  public function __construct()   

The two search methods represent different ways of performing a search, depending on whether or not we have a location name or exact GPS coordinates. They simply set the required parameters and call the doAPICall method of the parent YahooAPI class:

  public function locationSearch($query,$in_location)   
   return $this->doAPICall();  
 public function positionSearch($lat,$long)  
   return $this->doAPICall();  

The extractResults method saves us entering ['ResultSet']['Result'] all the time when we want to output the results, because the data we need will always be within that part of the returned array:

  public function extractResults()   
   $return = $this->getResults();  
   $return = $return['ResultSet']['Result'];  
   return $return;  

You'll find a copy of the code in the archive for the article. Keep it handy because we'll be using it in our example mashup. We'll also build a similar class for the Maps API later, as it has some slightly different requirements.

Our example "pizza" search, executed using our new LocalSearch class, now looks like this:

$localSearch = new LocalSearch();  
$localSearch->locationSearch('Pizza','Palo Alto, CA');  
$output = $localSearch->extractResults();

That's much easier, don't you think?

Yahoo! Maps AJAX API

Perform a quick web search and you could find the web sites for these pizza places, each of which would list the restaurant's address. But why would you go to all that trouble when Yahoo! provides all this data in the returned array -- as well as latitude and longitude information? Here's an example of the data returned:

[Title] => Patxi's Chicago Pizza   
[Address] => 441 Emerson St  
[City] => Palo Alto  
[State] => CA  
[Phone] => (650) 473-9999  
[Latitude] => 37.445265  
[Longitude] => -122.163432

Now that we have the location information, we need to figure out how to plot it on a map. Yahoo! provides a map image API, offering raw images of maps in PNG format, and (in theory) we could use GD to draw markers on the map. However, since we're building a web application, we can instead use the Maps AJAX API to generate a UI-friendly, interactive Yahoo! maps display. We can then add markers to the map in preset positions, using the bundled functions. (Note that the Maps AJAX API isn't really an Ajax API! In fact, there isn't any real Ajax at all -- that is, there are no XMLHttpRequest calls -- but due to the fact that the term Ajax has come to represent any web page technology that uses JavaScript and doesn't need to reload the web page to update itself, Ajax would be the best way to describe it.)

Unlike the other Yahoo! APIs, the Maps AJAX API isn't a REST-based web service. Instead, you have to include a JavaScript file on your page, create an instance of the map in a container on the page (usually a <div>) and manipulate it through JavaScript calls. Luckily, the HTML and JavaScript required are quite simple. Take a look at the mapoutput.php example in the code archive. This is all the JavaScript you'll need to generate the map:

var ymap = new YMap(document.getElementById('mC'),YAHOO_MAP_REG);   
var mPoint = new YGeoPoint(37.4041960114344,-122.008194923401);  
ymap.drawZoomAndCenter(mPoint, 3);  
var marker = new YMarker(mPoint);  
marker.addAutoExpand('<div class="mp">Some Text</div>');  

The first line creates a new instance of the YMap class, and assigns it to the element on the page with an ID of 'mC'. The second argument represents the desired map type, in this case a regular map rather than satellite imagery, YAHOO_MAP_SAT, or a hybrid of the two, YAHOO_MAP_HYB. The second line creates a YGeoPoint object, a point on the map based on latitude and longitude coordinates, while the third line calls the map object and tells it to centre itself on this new point and display the map, at a zoom level of 3.

The final three lines of JavaScript create a YMarker object, a visual map marker that expands to reveal some extra content when it's moused over. Our challenge is to generate all this with PHP, and to make the job easy, we're going to build a class that generates all the code for us.

Mashup Time!

Now that we've sorted out how to query the APIs and deal with the data, it's mashup time! As I mentioned before, we'll create a simple application that finds places with the local search API and, using the latitude and longitude coordinates from the returned search data, marks the exact locations of these places on a map from the maps API. And of course we'll wrap all the functionality up in a simple PHP class. The AJAX map API uses JavaScript code, so we'll use our PHP class to generate the required JavaScript based on the returned search data.

First, we'll start by querying the Maps API. I'll use the client class for the local search API, which I demonstrated earlier, to execute this sample query: 'Pizza' in 'Palo Alto, CA'. We need an instance of the LocalSearch class, and we'll use its locationSearch method to execute the API query. The extractResults method will give us the data that we want to work with. Now that we've built our client classes, all this can be achieved in three lines of code:

$localSearch = new LocalSearch();   
$localSearch->locationSearch('Pizza','Palo Alto, CA');  
$apiOutput = $localSearch->extractResults();

Let's take a step back for a moment and call print_r($apiOutput) to see what we have. The array $apiOutput now contains a number of sub-arrays, each of which is a single search result and contains (among other things) a 'Title', 'Latitude' and 'Longitude'. That's all we need for the moment, so let's quickly extract this information and delete the rest:

foreach($apiOutput as $id => $result)   
 $points[$id] = array($result['Title'],  

Here are some sample values from our newly defined $points array:

[0] => Array   
 [0] => Patxi's Chicago Pizza  
 [1] => 37.445265  
 [2] => -122.163432  
[1] => Array  
 [0] => Papa Murphys Pizza Take & Bake  
 [1] => 37.433243  
 [2] => -122.129291  

For each marker we want to put on our map, we need to know its position, and we need some summary text that we can have appear when the user mouses over it. In this case, when visitors mouse over one of our markers, we'll show them the name of the place.

Now that we have all our locality information, we come to the tricky bit -- generating the map HTML and JavaScript. Basically, our map code consists of two distinct sections -- the <head> HTML and CSS (for the map container), and the <body> HTML and JavaScript. The <body> includes the container <div> for the map and some JavaScript for the Maps AJAX API. For each marker we want to add to the map, we need a JavaScript YGeoPoint object to define its position, and a YMarker object to be the marker itself. We then customise the marker through the addLabel and addAutoExpand methods (many more are documented here) before placing it on the map using the map object's addOverlay method. We'll now create a PHP class that takes care of generating all of this JavaScript code, and call it AjaxMap.

Here's a summary of the methods our class will have:

  • getHeadHTML for generating <head> code
  • getMapScript for generating <body> code
  • initMarker for generating code for each marker

We'll also add some helper methods for customising the map:

  • setMapType for choosing between maps, satellite images, and hybrids
  • setMapContainer for setting the ID of the map container <div>
  • addMarker for adding markers to the map

Let's begin our AjaxMap class:

class AjaxMap    
 private $mapContainer;    
 private $mapType;    
 private $markers = array();    
 public $showZoom;    
 public $showPan;

We begin by including the YahooAPI class, which we'll use to generate the Yahoo! API calls. Our class has three private properties: $mapContainer will contain the ID of the HTML element acting as the map container, $mapType will represent the type of map desired and must be one of YAHOO_MAP_REG, YAHOO_MAP_SAT or YAHOO_MAP_HYB, and the final private property, $markers will contain an array of map location markers. The API offers the ability to add zoom and pan controls, so we'll add the public properties $showZoom and $showPan, which can be set to true when required.

So, first to the easy methods: getHeadHTML, the set functions and addMarker. All the getHeadHTML method needs to do is return a <script> tag referencing the Yahoo! AJAX Map API:

public function getHeadHTML()    
   return '<script type="text/javascript" '.    

The set functions are just as simple -- they act as wrapper methods for modifying private properties. Here's the code:

  public function setMapContainer($id)    
   $this->mapContainer = $id;    
 public function setMapType($type)    
   $this->mapType = $type;    

The addMarker method will add a new map marker entry to the private $markers array and takes a latitude value, a longitude value and description text as its arguments:

  public function addMarker($lat,$long,$descr)    
   $this->markers[] = array($lat,$long,$descr);    
initMarker is a private method called for each of the desired map markers and generates the JavaScript code required for the marker:

  private function initMarker($id,$lat,$long,$descr,$init_geo = TRUE)    
   $js = '';    
   if($init_geo) $js .= "nvar mPoint$id = ".    
       "new YGeoPoint($lat,$long);n";    
   $js .= "var currmarker = new YMarker(mPoint$id);n";    
   $js .= "currmarker.addLabel('$id');n";    
   $js .= "currmarker.addAutoExpand('<div class="mp">".    
   $js .= "ymap.addOverlay(currmarker);nn";    
   return $js;    
initMarker takes all the information about the marker -- latitude and longitude for position, a short description and some notes, plus a unique 'id' parameter -- and generates the JavaScript we need in order to draw the marker. The $init_geo parameter for initMarker indicates whether or not we need to create a YGeoPoint object for the marker; this may already have been done.

All that's left to do is bring everything together within the main JavaScript block. The getMapScript method will generate this JavaScript and assign it to the $js variable:

  public function getMapScript()    
   $js = '';

First, we have to initialise a YMap object. This is our main map object which will handle the drawing and customisation of the map. The first part is simple -- we output the code required to create a new YMap object:

    $js .= 'var ymap = new YMap(document.getElementById(''.    

In this instance, the properties $mapContainer and $mapType include the relevant information about the map, so setMapType and setMapContainer should be called before getMapScript.

Next, we output the JavaScript to add the zoom and pan controls if $showZoom and $showPan are set to true. To add a zoom control in JavaScript, we use the addZoomShort method of the YMap object, and addPanControl for a pan control:

    if($this->showZoom) $js .= "ymap.addZoomShort();n";    
   if($this->showPan) $js .= "ymap.addPanControl();n";

We may have a number of markers to display, but the map can only be centred on one of them. To keep it simple, we'll remove the last marker from the main set of markers, centre the map on it and draw it on the map before proceeding to draw the remaining markers. Obviously, none of this is needed if no markers are to be drawn on the map, so we check that markers exist here too. Here's the code that outputs the JavaScript required for centring the map on the last marker, and drawing that marker:

    if(count($this->markers) > 0)    
     $lastmarker = array_pop($this->markers);    
     $js .= 'var mPoint'.count($this->markers).' = new YGeoPoint('.    
     $js .= 'ymap.drawZoomAndCenter(mPoint'.count($this->markers).    
         ", 3);n";    
     $js .= $this->initMarker(count($this->markers), $lastmarker[0],    
         $lastmarker[1], $lastmarker[2],    

First we check if there are more than 0 markers (that is, we see if any have been set), and if so, extract the last of these markers and use that marker's data to write the JavaScript required to create a new YGeoPoint object. We then output the JavaScript required to draw the map, centre it on our last marker and set the zoom level to 3. In JavaScript, we do this via the drawZoomAndCenter method of the YMap object. We then call our initMarker function to generate the rest of the JavaScript, and through its last parameter, tell it not to output the JavaScript to create a YGeoPoint object, as we've already taken care of it.

Finally, we generate the code for each remaining marker by quickly iterating over the markers array, calling initMarker for each one and returning the $js string variable:

      foreach($this->markers as $id=>$obj)    
       $js .= $this->initMarker($id,$obj[0],$obj[1],$obj[2],TRUE);    
   return $js;    

That also represents the end of our AjaxMap class!

Now we just have to use our local search class and AjaxMap class in a proper application. I've put together a quick demonstration. First we need to include our two classes:


Next, we use our local search class to search for "pizza". We collect the locations from our search results and store them in an array called $points:

$localSearch = new LocalSearch();    
$localSearch->locationSearch('Pizza','Palo Alto, CA');    
$apiOutput = $localSearch->extractResults();    
foreach($apiOutput as $id => $result)    
 $points[$id] = array($result['Title'],    

We then create a new AjaxMaps object and add to it all our locations:

$ajaxMap = new AjaxMap();    
$ajaxMap->showPan = true;    
$ajaxMap->showZoom = true;    
foreach($points as $point)    

Now that all our location markers have been added to our AjaxMap object, the only task that's left to do is write the page HTML and output the JavaScript:

<!DOCTYPE html public "-//W3C//DTD XHTML 1.0 Transitional//EN"    
<html xmlns="">    
 <?php echo $ajaxMap->getHeadHTML(); ?>    
     #mC {    
       height: 500px;    
       width: 500px;    
     .mp {    
   <div id="mC"></div>    
   <script type="text/javascript">    
   <?php echo $ajaxMap->getMapScript(); ?>    

The entire script is available in the code archive. Set your application IDs, load it up on your web server, and with any luck you should see something like this:

Our app in action!

Congratulations! You've just built a mashup using the Yahoo! APIs. With a bit of tweaking, you could add search functionality, allowing the user to look for more than just 'Pizza' in 'Palo Alto, CA'. You could even integrate the functionality into an existing application (although be aware of the terms of use for both APIs). The possibilities are endless.

Where to From Here?

As you can see, exploiting the Yahoo! APIs with PHP5 to create useful mashups is a piece of cake, and there are many interesting applications that can be built with the data. Rasmus Lerdorf himself has written a similar article, taking a more in depth look at the Yahoo! Geocoding API, and how to easily use it with PHP5. It's also worth noting that while we've used the output=php parameter throughout this article, most of the APIs also offer JSON output for use via Ajax. The Yahoo! Developer Network's PHP Developer Center has an excellent collection of tutorials, code samples and other resources for consuming the APIs with PHP5.

Also check out Yahoo's Application Gallery for inspiration and to see some great web apps built with various Yahoo! APIs, If you build an interesting application, submit it to the gallery for some excellent exposure and useful feedback.

Update: The Zend PHP Framework also includes a collection of similar object-oriented interfaces for the Yahoo! APIs, which in many cases may be preferable to developing your own classes. The interfaces lie within the framework's Zend_Service package.

Login or Create Account to Comment
Login Create Account
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?