Twitter Delicious Facebook Digg Stumbleupon Favorites More

Thứ Tư

Lấy kết quả tìm kiếm từ Google qua các A

Từ giữa năm 2002 Google đã cung cấp các API cho phép người dùng truy xuất trực tiếp đến các nội dung: search result, suggestion, cached page mà không cần vào trang web. Bạn có thể vào để xem thông tin chi tiết rồi đăng kí 1 tài khoản (sẽ được cung cấp 1 số serial, có nó mới sử dụng các API được). Với tài khoản này bạn có thể thực hiện miễn phí 1000 yêu cầu tìm kiếm trong 1 ngày. Đây là dịch vụ rất ích lợi với các webmaster, thí dụ bạn có thể dùng nó để nghiên cứu về một từ khóa hoặc một trang web chẳng hạn.
Dịch vụ web của Google dựa trên SOAP. Với PHP (Google đã có sẵn thí dụ cho .NET và Java) bạn có thể dùng gói PEAR::SOAP thông qua thí dụ ở hoặc dùng một cài đặt khác là nusoap () như thí dụ ở
Cài đặt 1 (dùng PEAR::SOAP, bạn cần có package này trên server)

PHP Code:
<?php
/* Accessing the Google Web API via PHP
- by Simon Willison (simon@incutio.com)
This code is in the public domain - do whatever you want with it

To use this code you will need both PEAR and the PEAR SOAP package
installed somewhere on your php include path. You can get the SOAP
package from CVS:

cvs -d :pserver:cvsread@cvs.php.net:/repository login
(enter phpfi as the password)
cvs -d :pserver:cvsread@cvs.php.net:/repository co pear/SOAP

You will need a Google license key - see this site:
http://www.google.com/apis/

*/

include("SOAP/Client.php");

// Google search query
$query = 'soap';

// Your google license key
$key = 'xxxxxxxxxxxxxxxxxxxxxxxxx';

$s = new SOAP_Client('http://api.google.com/search/beta2');
$result = $s->call('doGoogleSearch', array(
'key' => $key,
'q' => $q,
'start' => 0,
'maxResults' => 10,
'filter' => false,
'restrict' => '',
'safeSearch' => false,
'lr' => '',
'ie' => '',
'oe' => '',
), 'urn:GoogleSearch');

// Is result a PEAR_Error?
if (get_class($result) == 'pear_error')
{
$message = $result->message;
$output = "An error occured: $message<p>";
}
else
{
// We have proper search results
$num = $result['estimatedTotalResultsCount'];
$elements = $result['resultElements'];
$list = '';
if ($num > 0) {
foreach ($elements as $item) {
$size = $item['cachedSize'];
$title = $item['title'];
$url = $item['URL'];
$snippet = $item['snippet'];
$desc = "<p><b>$title</b> - <a href=\"$url\">$url</a> ";
$desc .= "<small>[Size: $size]</small></p>";
$desc .= "\n<blockquote>$snippet</blockquote>\n\n";
$list .= $desc;
}
}
$output = "$num results returned:\n\n$list";
}
echo $output;
?>
Cài đặt 2 (dùng nusoap ), có chức năng đề nghị lỗi chính tả

PHP Code:
<?php

////////////////////////////////////////////////////////////
// This is example code of how to query the Google API using
// Web Services, SOAP, and PHP.
//
// Author: Geoff Peters, January 6th 2004.
// Updated by Dan Karran, 10th March 2005 to utilise nuSOAP instead of PEAR.


// put your developer's key here:
$key = 'INSERT GOOGLE API DEVELOPERS KEY';



include ('nusoap.php');

$soapclient = new soapclient('http://api.google.com/search/beta2');
$soapoptions = 'urn:GoogleSearch';

// Ensure there is a start value
if (!$start) {
$start = 0;
} else {
$start = intval($start-1);
}


////////////////////////////////////////////////////////////
// Calls the Google API and retrieves the search results in $ret
//
function do_search( $q, $type, $key, $start, &$ret )
{
global $soapclient;
global $soapoptions;


// Note that we pass in an array of parameters into the Google search.
// The parameters array has to be passed by reference.
// The parameters are well documented in the developer's kit on the
// Google site http://www.google.com/apis


// limit searches to this server
$sitequery = "$q site:{$_SERVER['SERVER_NAME']} $restrict";

$params = array(
'key' => $key,
'q' => $sitequery,
'start' => $start,
'maxResults' => 10,
'filter' => false,
'restrict' => '',
'safeSearch' => false,
'lr' => '',
'ie' => '',
'oe' => ''
);

// Here's where we actually call Google using SOAP.
// doGoogleSearch is the name of the remote procedure call.

$ret = $soapclient->call('doGoogleSearch', $params, $soapoptions);

$err = $soapclient->getError();

if ($err)
{
print("<br>An error occurred!<br>");
print(" Error: $err<br>\n");
return false;
}

return true;
}


////////////////////////////////////////////////
// Does Google search with retry.
// Retry is useful because sometimes the connection will
// fail for some reason but will succeed when retried.
function search( $q, $type, $key, $start, &$ret )
{
$result = false;
$max_retries = 5;
$retry_count = 0;

while( !$result && $retry_count < $max_retries )
{
$result = do_search( $q, $type, $key, $start, $ret );
if( !$result )
{
print( "Attempt $retry_count failed.<br>\n");
}
$retry_count++;
}
if( !$result )
{
print("<br>Sorry, connection to Google failed after retrying several times.<br>\n");
}
return $result;
}


////////////////////////////////////////////////////////////
// Calls the Google API and retrieves the suggested spelling correction
//
function do_spell( $q, $key, &$spell )
{
global $soapclient;
global $soapoptions;

$params = array(
'key' => $key,
'phrase' => $q,
);

$spell = $soapclient->call('doSpellingSuggestion', $params, $soapoptions);

$err = $soapclient->getError();

if ($err)
{
print("<br>An error occurred!<br>");
print(" Error: $err<br>\n");
return false;
}

return true;
}


//////////////////////////////////////////////////////////
// The main part of this script


if( $q != "" )
{
// remove the slashes that are automatically added by PHP before each quotation mark
$q = stripslashes($q);

if( do_search( $q, $type, $key, $start, $ret ) )
{

$count = $ret['estimatedTotalResultsCount']; // total number of results
$secs = round($ret['searchTime'],2); // time taken to search (in seconds)
$min = $ret['startIndex']; // first record returned
$max = $ret['endIndex']; // last record returned

if ($max) {

// Truncate query for display
if (strlen($q) > 36) {
$short_q = substr($q,0,33)."...";
} else {
$short_q = $q;
}

// print header with search box and details of search results
print "<form method=\"GET\"><table class=\"search_top\" width=100%><tr><td nowrap style=\"text-align:left;\">";
print "<input type=\"text\" name=\"q\" size=\"30\" value=\"$q\">\n";
print "<input type=\"submit\" value=\"search\">\n";
print "</td><td nowrap> results <b>$min</b> - <b>$max</b> of about <b>$count</b> for <b>$short_q</b> ";
print " (<b>$secs</b> seconds)&nbsp;</td></tr></table></form>";

// list results
foreach($ret['resultElements'] as $result) {

// Make URLs more friendly for user by removing http:// and highlighting where necessary
$friendly_URL = $result['URL'];
$friendly_URL = str_replace("http://","",$friendly_URL);
$friendly_URL = str_replace("$q","<b>$q</b>",$friendly_URL);

print "<p class=\"search_result\">";
if (!$title = $result['title']) {
$title = $result['URL'];
print "<a href=\"".$result['URL']."\">".$friendly_URL."</a>\n";
} else {
print "<a href=\"".$result['URL']."\">".$title."</a><br/>\n";
if ($result['snippet']) {
print $result['snippet']."<br/>\n";
}
print "<span class=\"search_url\">$friendly_URL</a>";
}
print "</p>\n\n";
}
} else {

print "<p>Sorry, no results were found on this site for <b>$q</b>. ";
do_spell($q, $key, $spell);
if ($spell[0]) {
print "Did you mean <b><a href=\"../search/?q=".$spell."\">".$spell."</a></b>? ";
}
print "Occasionally no results will be returned when there are problems with the link between this site and Google. If you believe the information is on the site but it tells you that it's not, please try again.</p>";
}
}
}

// Show forward/backward navigation if there are results
if ($count) {
print "<div class=\"search_bottom\">";
if ($min>1) {
if ($min >10) {
$prevpage = $min-10;
} else {
$prevpage = 1;
}
print " <b><a href=\"../search/?q=".$q."&start=".$prevpage."\">previous page</a></b> | ";
} else {
print " previous page | ";
}
if ($count>$max) {
$nextpage = $max+1;
print " <b><a href=\"../search/?q=".$q."&start=".$nextpage."\">next page</a></b> ";
} else {
print " next page ";
}
print "</div>";
}

print "<form method=\"GET\" class=\"search_main\">";
print "<input type=\"text\" name=\"q\" size=\"32\" value=\"$q\"> <input type=\"submit\" value=\"search\">";
print "</form>";

?>
Theo hainam

0 nhận xét:

Đăng nhận xét

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates