Using Yahoo! The search API develops its own-php version _php base

Source: Internet
Author: User
Tags parse error php example php foreach php script tagname yahoo co

U.S. Eastern Time March 1, Yahoo co-founder of one of the founders of Jerry Yang will announce the company's search network will enter the Web services. Yahoo Search Developer Network was set up in the Www.developer.yahoo.com website, and the company plans to hold a search engine strategy conference in New York (Search Engine Strategies Conference) on the launch of the plan. The network will allow developers to build new applications on top of Yahoo's search, including images, videos, news, and regional searches. Members who want to use this service must first go to http://api.search.yahoo.com/webservices/register_application to apply for a self ID number, note: Each ID number can only be searched 5,000 times per day.

Let's take a look at how to use PHP script to invoke Yahoo! The search API implements the results of the searches, all scripts are as follows:

<?php
Yahoo Web Services PHP Example Code
Rasmus Lerdorf
Www.knowsky.com

$appid = ' Yahoodemo ';
Enter the ID number of your application here

$service = Array (' image ' => ' Http://api.search.yahoo.com/ImageSearchService/V1/imageSearch '),
' Local ' => ' Http://api.local.yahoo.com/LocalSearchService/V1/localSearch ',
' News ' => ' Http://api.search.yahoo.com/NewsSearchService/V1/newsSearch ',
' Video ' => ' Http://api.search.yahoo.com/VideoSearchService/V1/videoSearch ',
' Web ' => ' http://api.search.yahoo.com/WebSearchService/V1/webSearch ');
?>
<body>
<form action= "yahoosearchexample.php" method= "Get" >
Search Term: <input type= "text" name= "query"/><br/>
Zip Code: <input type= "text" name= "Zip"/> (for local search) <br/>
<input type= "Submit" value= "go! "/>
<select name= "Type" >
<?php foreach ($service as $name => $val) {
if (!empty ($_request[' type ')) && $name = = $_request[' type '])
echo "<option selected> $name </option>\n";
else echo "<option> $name </option>\n";
}?>
</select>
</form>
<?php
function done () {?>
</body><?php
Exit
}

if (Empty ($_request[' query ')) | | |!in_array ($_request[' type '],array_keys ($service)) done ();

Ok, here we go, we have the query and the type of search are valid
The query
$q = ' query= '. Rawurlencode ($_request[' query ');
if (!empty ($_request[' zip ')) $q. = "&zip=". $_request[' Zip '];
if (!empty ($_request[' start ')) $q. = "&start=". $_request[' start '];
$q. = "&appid= $appid";

Then send it to the appropriate service
$xml = file_get_contents ($service [$_request[' type ']]. $q);

//Parse the XML and check it for errors
if (! $dom = Domxml_open_mem ($xml, domxml_load_parsing, $error)) {
  E Cho "XML parse error\n";
  foreach ($error as $errorline) {
 /* For production should obviously is logged to a file inst EAD */
    echo $errorline [' errormessage ']. " <br/>\n ";
    echo "node :". $errorline [' nodename ']. "<br/>\n";
    echo "line :". $errorline [' line ']. "<br/>\n";
    echo "Column:". $errorline [' col ']. "<br/>\n";
 }
  Done ();
}

Now traverse the DOM and this function
It is basically a generic parser this turns limited XML into a PHP array
With a couple of hardcoded tags which are common across all
Result XML from the Web services
function Xml_to_result ($dom) {
$root = $dom->document_element ();
$res [' totalresultsavailable '] = $root->get_attribute (' totalresultsavailable ');
$res [' totalresultsreturned '] = $root->get_attribute (' totalresultsreturned ');
$res [' firstresultposition '] = $root->get_attribute (' firstresultposition ');

$node = $root->first_child ();
$i = 0;
while ($node) {
Switch ($node->tagname) {
Case ' result ':
$subnode = $node->first_child ();
while ($subnode) {
$subnodes = $subnode->child_nodes ();
if (!empty ($subnodes)) foreach ($subnodes as $k => $n) {
if (Empty ($n->tagname)) $res [$i] [$subnode->tagname] = Trim ($n->get_content ());
else $res [$i] [$subnode->tagname][$n->tagname]=trim ($n->get_content ());
}
$subnode = $subnode->next_sibling ();
}
Break
Default
$res [$node->tagname] = Trim ($node->get_content ());
$i--;
Break
}
$i + +;
$node = $node->next_sibling ();
}
return $res;
}

$res = Xml_to_result ($dom);

Ok, now that we have the "results in" easy to use format,
Display them. It ' s quite ugly because I am using a single
Display loop to display every type and I don ' t really understand HTML
$first = $res [' firstresultposition '];
$last = $first + $res [' totalresultsreturned ']-1;
echo "<p>matched ${res[totalresultsavailable]}, showing $first to $last </p>\n";
if (!empty ($res [' Resultsetmapurl '])) {
echo "<p>result Set Map: <a href=\" ${res[resultsetmapurl]}\ ">${res[resultsetmapurl]}</a></p >\n ";
}
for ($i =0; $i < $res [' totalresultsreturned ']; $i + +) {
foreach ($res [$i] as $key => $value) {
Switch ($key) {
Case ' Thumbnail ':
echo "\n";
Break
Case ' Cache ':
echo "Cache: <a href=\" ${value[url]}\ ">${value[Url]}</a> [${value[size]}]<br/>\n";
Break
Case ' publishdate ':
echo "<b> $key:</b>". Strftime ('%x%x ', $value);
Break
Default
if (Stristr ($key, ' url ')) echo "<a href=\" $value \ "> $value </a><br/>\n";
else echo "<b> $key:</b> $value <br/>";
Break
}
}
echo "}

Create Previous/next Page Links
if ($start > 1)
Echo ' <a href= '/yahoosearchexample.php '.
' query= '. Rawurlencode ($_request[' query ').
' &zip= '. Rawurlencode ($_request[' zip ').
' &type= '. Rawurlencode ($_request[' type ')).
' &start= '. ($start-10). ' " ><-previous page</a> ';
if ($last < $res [' totalresultsavailable '])
Echo ' <a href= '/yahoosearchexample.php '.
' query= '. Rawurlencode ($_request[' query ').
' &zip= '. Rawurlencode ($_request[' zip ').
' &type= '. Rawurlencode ($_request[' type ')).
' &start= '. ($last + 1). ' " >next page-></a> ';
Done ();
?>

Interested friends can also look at the ASP version produced by the [Dynamic Web site Production Guide]: http://www.knowsky.com/yahoo/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.