Fetching Search Results as Serialized Arrays with Yahoo Web Services and PHP 5

In this second article of the series dealing with the implementation of some of the most useful web services offered by Yahoo! with PHP 5, I’ll show you how to parse the results returned by a determined web search service using a few array PHP processing functions.

Many modern web sites use popular web services, such as image and video searches. Their correct implementation has proven to be very useful when it comes to attracting new visitors that are looking for a richer and more productive surfing experience.

However, as you’ll possibly know, using a given web service in conjunction with a powerful server-side scripting language like PHP 5 can be quite challenging. This is particularly true if the web service must be implemented from scratch using WSDL (Web Service Description Language).

Fortunately, there are some frameworks available on the web that will let you easily use a determined web service without having to deal directly with data delivered in XML format. And that’s precisely the case with Yahoo! Web Search Services, which can be directly invoked within your own PHP applications by writing only a few lines of code.

Naturally, if you already went through the first article of the series, then you’ll surely be very familiar with using these web services provided by Yahoo! straight from a simple PHP script. As you’ll possibly recall, during that tutorial I built some illustrative hands-on examples aimed at demonstrating how to utilize Yahoo!’s Image and Video Search Services, among others, using only small pieces of PHP 5 code.

The results returned by these hands-on examples, after querying one of the aforementioned web services, always outputted in XML format. This can be rather intimidating for some PHP developers who want to implement those services within the context of their own applications.

Nevertheless, the good news is that all of the web services offered by Yahoo! permit the specification of an additional “output=php” parameter within the corresponding query string, which indicates that all of the results retrieved should be returned in the form of a serialized PHP array. Indeed, as you can see, this feature simplifies displaying the respective search results in a more readable format, since PHP has plenty of native functions aimed at processing array elements.

Now, having introduced the primary subject of this tutorial, let’s learn how to fetch results returned by the different Yahoo! Search Web Services in the form of serialized PHP arrays. Let’s get started!

{mospagebreak title=Displaying web services search results in XML format}

In case you didn’t have the chance to read the first article of the series, I’m going to list the source code of a couple of practical examples that I developed in that tutorial. Reviewing these examples will help you to more quickly grasp how to invoke different Yahoo! Search Services directly from your own PHP 5 scripts.

Are you ready to digest all this useful material? Great! These hands-on examples look like this: 

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

try{

$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();

}

/* displays the following:

<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>

{mospagebreak title=Next Example}

For the sake of clarity and considerations of length, we placed the second example on a new page. Here it is: 

<!–

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

–>

*/

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

try{

$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();

}

/* displays the following

<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

–>

*/


Despite the lengthy source code of the two previous hands-on examples, the truth is that they’re very easy to understand. In the first case, a GET http request is triggered to the corresponding Yahoo! URL in order to use its popular Web Search Service. Note that in the query string I included first the corresponding application ID (which can be obtained by completing a simple registration form), then the search term “Madonna,” and finally the number of results that should be returned to the client.

Next, the pertinent results are displayed on the browser in XML, wrapped by a pair of <ResultSet></ResultSet> nodes. Very simple to code and read, right?

And finally, the last example looks very similar to the first one, but in this case, the Video Web Search service is used instead of performing a common search.

So far, so good. At this time, hopefully you’ve recalled how to implement the previous Yahoo! Web Search Services directly from some simple PHP 5 scripts. What’s next? Well, as I explained in the beginning of this article, Yahoo! provides web developers with an additional “output” option for specifying in the query string which format the pertinent search result should be returned to the browser.

If you’re working with PHP, this “output” variable must have a value of “php” (output=php), which will cause all of the search results to be returned to the client in the form of a serialized PHP array. As you’ll realize, this feature can help, largely parsing these results using only a few PHP array processing functions, but this topic will be discussed in detail in the section to come.

So read the next few lines. They’re just one click away

{mospagebreak title=Serving outputs of Yahoo! Web services as serialized PHP arrays}

As I stated in the prior section, the results returned by a given Yahoo! Web Service can be retrieved in the form of a PHP serialized array by specifying an “output=php” option within the corresponding query string.

To see in detail how this process works, study the following code sample. It first queries the Yahoo! Web Search service with the same “Madonna” search term, and then returns the results as a serialized PHP array. Here it is:


try{

// example using Yahoo! Web Search Service – results are displayed specifying PHP output

$request=’http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=
Your-AP-ID &query=Madonna&results=2&output=php’;

// trigger the http request

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

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

}

$results=unserialize($results);

echo ‘print_r($results,TRUE)’;

}

catch(Exception $e){

echo $e->getMessage();

exit();

}


In the previous example, you can see that I specified that all of the search results returned by the Yahoo! Web Search Service must be retrieved in the form of a serialized PHP array.

In this case, the output generated by the previous script would be similar to this:


Array ( [ResultSet] => Array ( [type] => web [totalResultsAvailable] => 65700000
[totalResultsReturned] => 2 [firstResultPosition] => 1 [moreSearch]
=> /WebSearchService/V1/webSearch?query=Madonna&appid=Your-AP-
ID&region=us [Result] => Array ( [0] => Array ( [Title] => Madonna [Summary] =>
Official site of pop diva Madonna, with news, music, media, and fan club. [Url] =>
http://www.madonna.com/ [ClickUrl] =>
http://uk.wrs.yahoo.com/_ylt=A0Je5anQJxZH2HoAogndmMwF;
_ylu=X3oDMTB2cXVjNTM5BGNvbG8DdwRsA1dTMQRwb3MDMQRzZWMDc3IEdnRpZAM
-/SIG=11biuqam6/EXP=1192720720/**http%3A//www.madonna.com/ [DisplayUrl]
=> www.madonna.com/ [ModificationDate] => 1192518000 [MimeType] =>
text/html [Cache] => Array ( [Url] =>
http://uk.wrs.yahoo.com/_ylt=A0Je5anQJxZH2HoAowndmMwF;
_ylu=X3oDMTBwOHA5a2tvBGNvbG8DdwRwb3MDMQRzZWMDc3IEdnRpZAM-
/SIG=15v65vjvq/EXP=1192720720/**http%3A//66.218.69.11/search/cache%
3Fei=UTF-8%26appid=Your-AP-ID %26query=Madonna%26results=2%
26output=php%26u=www.madonna.com/%26w=madonna%
26d=ZjRUGudmPoUK%26icp=1%26.intl=us [Size] => 18519 ) ) [1] => Array
( [Title] => MySpace.com – Madonna – Pop / Rock – www.myspace.com/madonna
[Summary] => Madonna MySpace page with news, blog, music downloads,
desktops, wallpapers, and more. [Url] => http://www.myspace.com/madonna
[ClickUrl] => http://uk.wrs.yahoo.com/_ylt=A0Je5anQJxZH2HoApQndmMwF;
_ylu=X3oDMTB2ZjQ4dDExBGNvbG8DdwRsA1dTMQRwb3MDMgRzZWMDc3IEdnRpZAM
-/SIG=11infbg8f/EXP=1192720720/**http%3A//www.myspace.com/madonna
[DisplayUrl] => www.myspace.com/madonna [ModificationDate] => 1192518000
[MimeType] => text/html [Cache] => Array ( [Url] =>
http://uk.wrs.yahoo.com/_ylt=A0Je5anQJxZH2HoApgndmMwF;
_ylu=X3oDMTBwZG5hOWwzBGNvbG8DdwRwb3MDMgRzZWMDc3IEdnRpZAM-
/SIG=1663fh7ed/EXP=1192720720/**http%3A//66.218.69.11/search/cache%
3Fei=UTF-8%26appid=Your-AP-ID %26query=Madonna%26results=2%
26output=php%26u=www.myspace.com/madonna%26w=madonna%26d=Z-awV-
dmPogu%26icp=1%26.intl=us [Size] => 138157 ) ) ) ) )

As you can see, all the results produced by the corresponding search term have been returned in a serialized array, which was unserialized before being outputted to the browser. Although this array is actually multidimensional, it’s quite easy to extract certain elements for further processing. Quite simple to grasp, right?

At this point you learned not only how to implement the Yahoo! Web Search Service with PHP 5, but how to return the results as a serialized PHP array. Nevertheless, you’re probably wondering how this feature can be exploited in a useful manner. Well, as you saw in the previous example, it’s fairly simple to extract some of these array elements to display them in a more readable format using some fancy markup.

Thus, in the next section I’m going to teach you how perform this task with minor efforts, so click on the link below and keep reading.

{mospagebreak title=Iterating over array elements with PHP 5}

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?
appid=Your-AP-ID&query=Madonna&results=2&output=php';

// 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
[Url].’">’.$result[Url].'</a>';

}

}

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!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan