Using Yahoo! Web Services with PHP 5

In the last few years, the utilization of different web services has become very popular with web developers. This growing trend owes a lot to the development of so-called mashup applications, where many of these web services are put to work seamlessly in conjunction, generally using a server-side programming language that is common to all of them. This article, the first in a six-part series, will get you started with using the Yahoo! Developer Framework in PHP 5 to build some useful web services.

However, not all is so easy when it comes to implementing a specific web service, particularly if you’re a PHP programmer who’s taking the first steps into the vast and exciting area of modern web development. Admittedly, building a PHP 5 application that will interact in one form or another with a particular web service won’t always be a painless experience; it can be even more difficult if you don’t feel very inclined to work with data that is served in XML format.

Fortunately, not all is lost when you’re developing PHP 5 applications that will use a determined web service, since there are many frameworks available that will permit you to work with them without having to deal directly with XML. One framework that’s becoming quite popular with many PHP developers is the handy Yahoo! Developer Network, located at http://developer.yahoo.com, which offers plenty of thoroughly-documented APIs that allow you to implement popular web services, such as web and image searches directly on your own web sites, using this powerful friendly server-side scripting language.

Of course, there’s the possibility that you don’t want to do a lot of work understanding how these Yahoo! APIs can be used within the context of PHP-based applications, which is where this series comes in. In its different parts I’ll show you how to implement, with minor hassles, some of the most useful web services offered by Yahoo!, like web, image and video searches, all from inside your PHP 5 scripts.

In this case, it’s not my intention to provide you here with a fully-featured guide on how to use Yahoo!’s Web services with PHP 5, because the best place to go is simply the aforementioned Developer Network. Instead, I’ll offer to you a bunch of code samples that hopefully will assist you in the development of PHP 5 applications that will utilize some of these useful web services.

Now, having introduced the primary goal of this series, it’s time to get rid of the preliminaries and start learning how to utilize the different web search services provided by Yahoo!, by using some simple PHP 5 scripts. Let’s begin this educational journey now!

{mospagebreak title=Getting started using the Yahoo! Web Search services}

Before you start using a specific Yahoo! Web Service within your own PHP 5 scripts, first you should get an “Application ID,” which is a key provided by Yahoo! that will let you use the services in question in the scope of your web site’s domain. As you might guess, to get this application ID you must complete a simple registration form, and if all goes well, you should receive the key in your email inbox in a very short time. Nothing too difficult, actually.

Once you’ve received this key by email, then you’re ready to use the web services provided by Yahoo!, so considering that you’ve already completed this process successfully, it’s time to develop some code samples that will help you to grasp more clearly how to implement a specific web service with PHP 5.

All right, to begin with, a simple GET request must be triggered to the URL where a particular web service runs, in order to get its corresponding results. These results, unless you specify another format, will be returned as XML data.

To demonstrate how to make a request to the Yahoo! Web Search Service, below I coded an illustrative PHP 5 script, which first queries the mentioned web service using “Madonna” as the search term, and then fetches the corresponding results in XML format.

Now that I have explained how this sample script will work, please study its respective signature:


try{

// example using Yahoo! Search Web Service – search results are
displayed in raw XML format

$request=’http://search.yahooapis.com/WebSearchService/V1/
webSearch?appid=Your-AP-ID&query=madonna&results=4′;

// trigger the http request

if(!$results=file_get_contents($request)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

// display the results in XML format

header(‘Content-type:text/xml;charset=iso-8859-1′);

echo $results;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


As you can see, using the Yahoo! Web Search Service with PHP 5 is actually a no-brainer process that only requires a few lines of code. In this case, the above code snippet triggers the request to the proper URL, including into the query string the application ID that you got previously, then the pertinent search term and finally (this parameter is optional) the number of results that must be returned to the browser.

Lastly, these results are fetched by using the “file_get_contents()” PHP built-in function (make sure that “http” wrappers are enabled on your php.ini file), and displayed directly on the browser, in the following way:


<ResultSet xsi:schemaLocation="urn:yahoo:srch
http://api.search.yahoo.com/WebSearchService/V1/
WebSearchResponse.xsd" type="web"
totalResultsAvailable="65700000" totalResultsReturned="4"
firstResultPosition="1"
moreSearch="/WebSearchService/V1/webSearch?query=madonna&appid=
Your-AP-ID&region=us">

<Result>

<Title>Madonna</Title>

<Summary>Official site of pop diva Madonna, with news, music, media, and fan club.</Summary>

<Url>http://www.madonna.com/</Url>

<ClickUrl>http://uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBkjbdmMwF;
_ylu=X3oDMTB2cXVjNTM5BGNvbG8DdwRsA1dTMQRwb3MDMQRzZWMDc3IEdnRpZAM-
/SIG=11buvpo71/EXP=1192717835/**http%
3A//www.madonna.com/</ClickUrl>

<DisplayUrl>www.madonna.com/</DisplayUrl>

<ModificationDate>1192518000</ModificationDate>

<MimeType>text/html</MimeType>

<Cache>

<Url>http: //uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBkzbdmMwF;
_ylu=X3oDMTBwOHA5a2tvBGNvbG8DdwRwb3MDMQRzZWMDc3IEdnRpZAM-
/SIG=15ipfur0l/EXP=1192717835/**http%
3A//66.218.69.11/search/cache%3Fei=UTF-8%26appid= Your-AP-ID %
26query=madonna%26results=4%26u=www.madonna.com/%26w=madonna%
26d=ZjRUGudmPoUK%26icp=1%26.intl=us

</Url>

<Size>18519</Size>

</Cache>

</Result>

<Result>

<Title>MySpace.com – Madonna – Pop / Rock -
www.myspace.com/madonna</Title>

<Summary>Madonna MySpace page with news, blog, music downloads,
desktops, wallpapers, and more.</Summary>

<Url>http://www.myspace.com/madonna</Url>

<ClickUrl>http://uk.wrs.yahoo.com/_ylt=A0Je5aqLHBZHhCMBlTbdmMwF;
_ylu=X3oDMTB2ZjQ4dDExBGNvbG8DdwRsA1dTMQRwb3MDMgRzZWMDc3IEdnRpZAM-
/SIG=11i0d3vg8/EXP=1192717835/**http%3A//www.myspace.com/madonna

</ClickUrl>

<DisplayUrl>www.myspace.com/madonna</DisplayUrl>

<ModificationDate>1192518000</ModificationDate>

<MimeType>text/html</MimeType>

<Cache> <Url>http://uk.wrs.yahoo.com/_ylt=A0Je5aqLHBZHhCMBljbdmMwF;
_ylu=X3oDMTBwZG5hOWwzBGNvbG8DdwRwb3MDMgRzZWMDc3IEdnRpZAM-
/SIG=15pd5lje6/EXP=1192717835/**http%3A//66.218.69.11/search/cache%
3Fei=UTF-8%26appid= Your-AP-ID %26query=madonna%26results=4%
26u=www.myspace.com/madonna%26w=madonna%26d=Z-awV-dmPogu%
26icp=1%26.intl=us

</Url>

<Size>138157</Size>

</Cache>

</Result>

<Result>

<Title>Madonna (I)</Title>

<Summary>Facts and filmography for the singer and actress.</Summary>

<Url>http://www.imdb.com/name/nm0000187</Url>

<ClickUrl>http://uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBmDbdmMwF;
_ylu=X3oDMTB2M3MzdmZoBGNvbG8DdwRsA1dTMQRwb3MDMwRzZWMDc3IEdnRpZAM-
/SIG=11m0tssno/EXP=1192717835/**http%
3A//www.imdb.com/name/nm0000187

</ClickUrl>

<DisplayUrl>www.imdb.com/name/nm0000187</DisplayUrl>

<ModificationDate>1192518000</ModificationDate>

<MimeType>text/html</MimeType>

<Cache>

<Url>http://uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBmTbdmMwF;
_ylu=X3oDMTBwZ2dpZ2ZkBGNvbG8DdwRwb3MDMwRzZWMDc3IEdnRpZAM-
/SIG=15tn2vem4/EXP=1192717835/**http%
3A//66.218.69.11/search/cache%3Fei=UTF-8%26appid= Your-AP-ID %
26query=madonna%26results=4%26u=www.imdb.com/name/nm0000187%
26w=madonna%26d=DgNm1OdmPoYh%26icp=1%26.intl=us

</Url>

<Size>97655</Size>

</Cache>

</Result>

<Result>

<Title>Madonna Song Lyrics: Home Page</Title>

<Summary>Extensive collection of Madonna lyrics, organized by album. Includes lyrics to singles.</Summary>

<Url>http://www.madonnalyrics.org/</Url>

<ClickUrl>http://uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBmzbdmMwF;
_ylu=X3oDMTB2OWM1MXQ5BGNvbG8DdwRsA1dTMQRwb3MDNARzZWMDc3IEdnRpZAM-
/SIG=11h8ms67a/EXP=1192717835/**http%3A//www.madonnalyrics.org/

</ClickUrl>

<DisplayUrl>www.madonnalyrics.org/</DisplayUrl>

<ModificationDate>1181286000</ModificationDate>

<MimeType>text/html</MimeType>

<Cache>

<Url>http://uk.wrs.yahoo.com/
_ylt=A0Je5aqLHBZHhCMBnDbdmMwF;
_ylu=X3oDMTBwYzFnNmkxBGNvbG8DdwRwb3MDNARzZWMDc3IEdnRpZAM-
/SIG=15o801re7/EXP=1192717835/**http%
3A//66.218.69.11/search/cache%3Fei=UTF-8%26appid= Your-AP-ID %
26query=madonna%26results=4%26u=www.madonnalyrics.org/%
26w=madonna%26d=WcyQU-dmPohM%26icp=1%26.intl=us

</Url>

<Size>18749</Size>

</Cache>

</Result>

</ResultSet>

<!–

ws02.search.scd.yahoo.com uncompressed/chunked Wed Oct 17
07:30:35 PDT 2007

–>


Undoubtedly, at first glance the output returned by the Yahoo! Web Search service seems to be rather intimidating, but this is a mistaken impression. If you take a closer look at it, you’ll see that the entire output is wrapped into a pair of <ResultSet></ResultSet> nodes, and each of the pertinent results are contained in a pair of <Result></Result> tags too.

This obviously implies that it’s perfectly possible to build a simple XML parser with PHP 5 that displays these results in a more readable format, but this process is out of the scope of this article. In addition, if you’re interested in learning more on this topic, you may want to look at the bunch of examples created by Rasmus Lerdorf, which are available for educational purposes, on the aforementioned Yahoo! Developer Network’s official web site.

So far, so good. At this point I’m pretty sure that you grasped the logic that stands behind querying the Yahoo! Web Search Service with PHP 5. This is merely the beginning, however, since in the next section I’m going to show you how to implement the Video Search Service provided by Yahoo!, by using a script similar to the one coded previously.

To see how this brand new Yahoo! web service can be utilized with PHP 5, please go ahead and read the next few lines. I’ll be there, waiting for you.

{mospagebreak title=Implementing the Yahoo! Video Search Service with PHP 5}

In the previous section, you learned how to take advantage of the features offered by the Yahoo! Web Search Service, by coding only a simple PHP 5 script. Besides, once the pertinent service was queried with a sample search term, the corresponding results were returned to the browser in XML format, to be displayed on the browser.

So, considering that you understood the basics of using this web service, I’m going to teach you how to code a similar script. It will be focused on utilizing another popular web service provided by Yahoo!, namely the one that searches video files.

That being said, here’s the definition of this brand new script: 

try{

// example using Yahoo! Video Search Web Service – search results are displayed in raw XML format

$request=’http://search.yahooapis.com/VideoSearchService/V1/
videoSearch?appid=Your-AP-ID&query=madonna&results=4′;

// trigger the http request

if(!$results=file_get_contents($request)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

// display the results in XML format

header(‘Content-type:text/xml;charset=iso-8859-1′);

echo $results;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


 

Definitely that wasn’t rocket science, right? As you can see, in this case I modified only the URL of the web service being requested, at the beginning of the script, in order to retrieve four different video files associated with the search term “Madonna.”

Besides, since the script simply fetches these results in raw XML format, this is the output generated by it, after performing the pertinent search process:


<ResultSet xsi:schemaLocation="urn:yahoo:srchmv
http://api.search.yahoo.com/VideoSearchService/V1/
VideoSearchResponse.xsd" totalResultsAvailable="10365"
totalResultsReturned="4" firstResultPosition="1">

<Result>

<Title>madonna_2004_montage.wmv</Title>

<Summary>, interviews, news footage and tour clips from New York and Paris….here’s hoping 2005 is just as busy! Right Click And Save Target As Madonna’s 2004 Movie Montage (WMV) – 7:44 – 21.8Mb Noticias madonna – Noticias madonna – Noticias madonna </Summary>

<Url>http://madonnalicious.com/downloads/
madonna_2004_montage.wmv</Url>

<ClickUrl>http://madonnalicious.com/downloads/
madonna_2004_montage.wmv</ClickUrl>

<RefererUrl>http://www.descargaarchivos.com/noticias/index.php?
query=madonna&type=video</RefererUrl>

<FileSize>22902293</FileSize>

<FileFormat>msmedia</FileFormat>

<Height>240</Height>

<Width>320</Width>

<Duration>464</Duration>

<Streaming>false</Streaming>

<Channels>2</Channels>

<Thumbnail>

<Url>http://scd.mm-so.yimg.com/image/1702970034</Url>

<Height>105</Height>

<Width>140</Width>

</Thumbnail>

</Result>

<Result>

<Title>madonna_earlscourt_190804.wmv</Title>

 <Summary>http://www.madonnalicious.com/downloads/
madonna_gelredome_090904.wmv madonna 9sep
2004http://www.madonnalicious.com/downloads/
madonna_earlscourt_190804.wmv
http://www.madonnalicious.com/downloads/
madonna_arlscourt_dtm_190804.wmv</Summary>

<Url>http://www.madonnalicious.com/downloads/
madonna_earlscourt_190804.wmv</Url>

<ClickUrl>http://www.madonnalicious.com/downloads/
madonna_earlscourt_190804.wmv</ClickUrl>

<RefererUrl>http://lounge.cosmopolitan.nl/messages/1/14515.html?
1095249265</RefererUrl>

 <FileSize>42149471</FileSize>

<FileFormat>msmedia</FileFormat>

<Height>240</Height>

<Width>320</Width>

<Duration>543</Duration>

<Streaming>false</Streaming>

<Channels>2</Channels>

<Thumbnail>

<Url>http://scd.mm-so.yimg.com/image/1700163527</Url>

<Height>105</Height>

<Width>140</Width>

</Thumbnail>

</Result>

<Result>

<Title>madonna.al.et.mpg</Title>

<Summary>Summary: Watch Madonna on Entertainment Tonight : Madonna discusses American Life with ET .mpg Noticias madonna – Noticias madonna – Noticias madonna -</Summary>

<Url>http://steveswartz.com/madonna.al/madonna.al.et.mpg</Url>

<ClickUrl>http://steveswartz.com/madonna.al/
madonna.al.et.mpg</ClickUrl>

<RefererUrl>http://www.descargaarchivos.com/noticias/index.php?
query=madonna&type=video</RefererUrl>

<FileSize>12821508</FileSize>

<FileFormat>mpeg</FileFormat>

<Height>240</Height>

<Width>352</Width>

<Duration>73</Duration>

<Streaming>false</Streaming>

<Channels>2</Channels>

<Thumbnail>

<Url>http://scd.mm-so.yimg.com/image/1794815224</Url>

<Height>98</Height>

<Width>145</Width>

</Thumbnail>

</Result>

<Result>

<Title>madonna_jonathanross_ruperteverett.wmv</Title>

<Summary>And Save Target As Friday Night With Jonathan Ross – Rupert Everett On Madonna (WMV) – 1:25 – 2.45Mb Noticias madonna Noticias madonna – Noticias madonna</Summary>

<Url>http://www.madonnalicious.com/downloads/
madonna_jonathanross_ruperteverett.wmv</Url>

<ClickUrl>http://www.madonnalicious.com/downloads/
madonna_jonathanross_ruperteverett.wmv</ClickUrl>

<RefererUrl>http://www.descargaarchivos.com/noticias/index.php?
query=madonna&type=video</RefererUrl>

<FileSize>2579729</FileSize>

<FileFormat>msmedia</FileFormat>

<Height>240</Height>

<Width>320</Width>

<Duration>85</Duration>

<Streaming>false</Streaming>

<Channels>2</Channels>

<Thumbnail>

<Url>http://scd.mm-so.yimg.com/image/1703473304</Url>

<Height>105</Height>

<Width>140</Width>

</Thumbnail>

</Result>

</ResultSet>

<!–

ws05.search.scd.yahoo.com uncompressed/chunked Wed Oct 17
07:41:48 PDT 2007

–>


As shown above, the previous search returned the URL of four video files along with some additional information about them, such as their format and size, and the respective dimensions of the corresponding thumbnails as well.

Again, it’s clear to see here that those search results can be easily formatted in (X)HTML, only using a few lines of PHP code, but as I expressed earlier, I will leave you this task as homework (if you’re having trouble sleeping, you may want to try this).

All right, as you learned in the previous example, using the Yahoo! Video Search Service with PHP 5 is indeed a straightforward process that can be performed with minor hassles. Therefore it’s time to move on and code a final hands-on example. The example in question will be focused on querying the Yahoo! Image Search Service directly from a PHP 5 script.

As you might have guessed, this procedure will be discussed in the upcoming section, so click on the below link and keep reading. 

{mospagebreak title=Querying the Yahoo! Image Search Service with PHP 5}

As I explained in the section that you just read, the last hands-on example that I’m going to show you in this article will be aimed at demonstrating how to query the Yahoo! Image Search Service directly from inside a simple PHP 5 script.

Logically, this procedure is nearly identical to the one discussed in the prior section. Its main difference rests on the URL where the web service in question has to be queried. But let me go straight to the point and show you how to use this helpful Yahoo! Service with PHP 5. Take a look at the following code sample:


try{

// example using Yahoo! Image Search Web Service – search results are displayed in raw XML format

$request=’http://search.yahooapis.com/ImageSearchService/V1/
imageSearch?appid=Your-AP-ID&query=madonna&results=2′;

// trigger the http request

if(!$results=file_get_contents($request)){

throw new Exception(‘Error requesting Yahoo! Web service’);

}

// display the results in XML format

header(‘Content-type:text/xml;charset=iso-8859-1′);

echo $results;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


// displays the following

/*

<ResultSet xsi:schemaLocation="urn:yahoo:srchmi
http://api.search.yahoo.com/ImageSearchService/V1/
ImageSearchResponse.xsd" totalResultsAvailable="684079"
totalResultsReturned="2" firstResultPosition="1">

<Result>

<Title>Madonna_vogue.jpg</Title>

<Summary>Madonna_3.jpg 30-Apr-2005 14:34 23k Madonna_9.jpg 30-
Apr-2005 14:34 23k Madonna_vogue.jpg 30-Apr-2005 14:35 22k
Madonna_13.jpg 30-Apr-2005 14:34 22k</Summary>

<Url>http://www.multinet.no/~jonarne/Hjemmesia/Favorittartister/
madonna/Madonna_vogue.jpg</Url>

<ClickUrl>http://www.multinet.no/~jonarne/Hjemmesia/
Favorittartister/madonna/Madonna_vogue.jpg</ClickUrl>

<RefererUrl>http://www.multinet.no/~jonarne/Hjemmesia/
Favorittartister/madonna?S=D</RefererUrl>

<FileSize>22835</FileSize>

<FileFormat>jpeg</FileFormat>

<Height>409</Height>

<Width>299</Width>

<Thumbnail>

<Url>http://sp1.mm-a7.yimg.com/image/3729207548</Url>

<Height>140</Height>

<Width>102</Width>

</Thumbnail>

</Result>

<Result>

<Title>madonna_90563a.jpg</Title>

<Summary>ANGRER: Madonna spiller gjerne pa sex for a provosere, men angrer pa boken Sex.- Jeg lurer stadig pa hva som motiverte meg til a lage den, sier hun om sin vagale bok, Sex , som vakte</Summary>

<Url>http://pub.tv2.no/multimedia/TV2/archive/00090/
madonna_90563a.jpg</Url>

<ClickUrl>http://pub.tv2.no/multimedia/TV2/archive/00090/
madonna_90563a.jpg</ClickUrl>

<RefererUrl>http://pub.tv2.no/TV2/underholdning/kjendiser/
madonna/article104130.ece</RefererUrl>

<FileSize>14540</FileSize>

<FileFormat>jpeg</FileFormat>

<Height>400</Height>

<Width>200</Width>

<Thumbnail>

<Url>http://sp1.mm-a4.yimg.com/image/2804555704</Url>

<Height>135</Height>

<Width>67</Width>

</Thumbnail>

</Result>

</ResultSet>

<!–

ws05.search.scd.yahoo.com uncompressed/chunked Wed Oct 17
08:02:55 PDT 2007

–>


As demonstrated above, using the Yahoo! Image Search Service with PHP 5 requires practically the same steps that you learned when using other web services. In this case, the pertinent results are retrieved by using the same “file_get_contents()” PHP native function that you saw before, and are also displayed on the browser in raw XML format.

Finally, taking into account that all of the code samples included in this tutorial might be the first ones that you learned concerning the implementation of the most common web services offered by Yahoo! with PHP 5, I suggest you to develop your own test examples to acquire a more solid background in this useful and interesting topic.

Final thoughts

That’s it for now. In this initial installment of the series, I showed you with some educational code samples how to query basically the four primary web search services provided by Yahoo! directly with PHP 5. As you saw earlier, in every case the corresponding search results were outputted in XML, but this is only momentary.

I’m saying this because in the next tutorial of the series I’m going to teach you how to utilize all these Yahoo! APIs to work specifically with PHP, and display the results returned by a given search query in the form of serialized arrays.

Now that you know what the upcoming part will be about, you won’t want to miss it!

[gp-comments width="770" linklove="off" ]

chat