การเรียกใช้เว็บเซอร์วิส REST ด้วยภาษา PHP นั้นง่ายและเป็นที่นิยม

ภาษา PHP เป็นภาษาที่เหมาะสมในการพัฒนาเว็บแอปพลิเคชัน เนื่องจากเป็นภาษาที่ง่าย
เรียนรู้ได้เร็ว และสามารถนำมาใช้ได้ฟรี  เว็บเซอร์วิสแบบ REST นั้นเป็นเว็บเซอร์วิสที่สามารถพัฒนาขึ้นมาได้ง่ายโดยอาศัยเพียงความรู้เกี่ยวกับ XML และ HTTP  การเรียกใช้เว็บเซอร์วิส REST ด้วยภาษา PHP นั้นง่ายและเป็นที่นิยม 

ขั้นตอนวิธีการมีดังต่อไปนี้

1) เรียกฟังก์ชัน Header() เพื่อที่จะทำให้ชนิดเนื้อหาที่เราอ่านผ่านเว็บเบราว์เซอร์อยู่ในรูปของภาษา XML เช่น

header('Content-Type: text/xml');

2) เรียกฟังก์ชัน file_get_contents() เพื่อที่จะดึงเนื้อหาทั้งหมดมาเก็บไว้ในตัวแปร เช่น

$xml = file_get_contents($url); 

ตัวอย่างของการเรียกใช้ Amazon Web services แบบ REST ในการค้นหาหนังสือที่มีคำสำคัญว่า Web Services  มีดังต่อไปนี้

<?php
header("Content-type: text/xml");
$base = 'http://webservices.amazon.com/onca/xml';
$query_string = '';
$params = array(
'Service' =>'AWSECommerceService',
'SubscriptionId' => '16XT8ETKKB7NWHAGCQ02' ,
'Operation' => 'ItemSearch',
'SearchIndex' => 'Books',
'Keywords' => 'Web Services');
foreach ($params as $key => $value) {
   if ($key != 'Keywords')
    $query_string .= "$key=" . urlencode($value) . "&";
  else
   $query_string .="$key=".urlencode($value);
}
$url = "$base?$query_string";

// In case you need to call Web services through Proxy, you need to define a context for HTTP.
/$aContext = array(
   'http' => array(
       // this is KKU proxy host and port
       'proxy' => 'tcp://202.12.97.116:8088',
       'request_fulluri' => True,
       ),
   );
/

// Now all file stream functions can use this context.
// $cxContext = stream_context_create($aContext);
// $xml = file_get_contents($url, False, $cxContext);
$xml = file_get_contents($url);
echo $xml;     
?>

ซึ่งเราก็จะได้ผลลัพธ์ดังรูปที่แสดงต่อไปนี้

 

อ้างอิงจาก 

PHP: file_get_contents -  Manual http://br.php.net/file_get_contents 

PHP: header - Manual http://th2.php.net/header