วันพุธที่ 8 สิงหาคม พ.ศ. 2550

HACK#55 การเขียนโปรแกรม Google Web API ด้วย PHP

ตัวอย่างง่ายๆในการโปรแกรม Google Web API ด้วย PHP และโมดูล NuSOAP

PHP (http://www.php.net) ซึ่งย่อมาจาก “PHP Hypertext Processing” เป็นภาษาสคริปต์ที่ใช้งานร่วมกับ HTML และได้รับการยอมรับเป็นอย่างมาก ในการพัฒนาโปรแกรมทางด้านเว็บ และสำหรับการเพิ่มโมดูลของ PHP ที่ชื่อ NuSOAP เข้าไป (http://dietrich.ganx4.com/nusoap) จะทำให้สามารถสร้างและใช้งาน SOAP based web service ได้

การแฮ็กในหัวข้อนี้ จะแสดงให้เห็นการใช้งาน PHP และ NuSOAP ในการทำงานร่วมกับ Google Web API

โค้ดตัวอย่าง

<!--

# googly.php

# A typical Google Web API php script

# Usage: googly.php?query=<query>

-->

<html>

<head>

<title>googly.php</title>

</head>

<body>

<?

# Use the NuSOAP php library

require_once('nusoap.php');

# Set parameters

$parameters = array(

'key'=>'insert key here',

'q' => $HTTP_GET_VARS['query'],

'start' => '0',

'maxResults' => '10',

'filter' => 'false',

'restrict' => '',

'safeSearch' => 'false',

'lr' => '',

'ie' => 'latin',

'oe' => 'latin'

);

# Create a new SOAP client, feeding it GoogleSearch.wsdl on Google's site

$soapclient = new soapclient('http://api.google.com/GoogleSearch.wsdl', 'wsdl');

# query Google

$results = $soapclient->call('doGoogleSearch',$parameters);

# Results?

if ( is_array($results['resultElements']) ) {

print "<p>Your Google query for '" . $HTTP_GET_VARS['query'] . "' found " . $results['estimatedTotalResultsCount'] . " results, the top ten of which are:</p>";

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

print

"<p><a href='" . $result['URL'] . "'>" .

( $result['title'] ? $result['title'] : 'no title' ) .

"</a><br />" . $result['URL'] . "<br />" .

( $result['snippet'] ? $result['snippet'] : 'no snippet' ) .

"</p>";

}

}

# No Results

else {

print "Your Google query for '" . $HTTP_GET_VARS['query'] . "' returned no results";

}

?>

</body>

</html>

Running the Hack

ดำเนินการแฮ็กด้วยวิธีการเดียวกันกับที่คุณทำในการเรียกใช้ CGI Script ทั่วไป โดยให้คุณใส่คำถาม (query) ที่ต้องการลงไปแทน your google query

http://localhost/googly.php?query=your google query

ผลลัพธ์

จากภาพที่ 5-1 เป็นการค้นหาด้วยคำว่า php

รูปที่ 5-1 ผลลัพธ์จากการค้นหาโดยใช้คำว่า PHP

0 ความคิดเห็น: