This post has already been read 4856 times!

webservice-There is a list at the official PHP website: http://www.php.net/manual/en/refs.webservice.php You can see that PHP can work with OAuth, SCA, SOAP, Yar and XML-RPC. But there is another way which is so simple to create a webservice. It is JSON.

How to create a simple web service with JSON

I will show how to create a simple web service with JSON. Our service will get the parameters by using $_GET , therefore we will put the parameters to url.
For instance : http://mywebserviceurl.com?s=myparameter so the service will answer depending on myparameter.

Lets look at service's index file

<strong>index.php </strong>
<?php
include('connectdb.php');
 
$something = $_GET['s'];
$sqlcode = mysql_query("Select $something from mydb limit 5 ");
 
$jsonObj= array();
while($result=mysql_fetch_object($sqlcode))
{
  $jsonObj[] = $result;
}
 
$final_res =json_encode($jsonObj) ;
echo $final_res;  

connectdb.php

    $hostname="localhost";
    $username=""; //write your username
    $password=""; //write your password
    $db_name=""; //write your db name
    $con=mysql_connect($hostname,$username,$password);
    mysql_select_db($db_name,$con) or die ("Cannot connect the Database");
    mysql_query("SET NAMES 'utf8'",$con); 
?>

Thats all. You will see the JSON results on the screen. You can validate the JSON results with the help of some sites.

Json validator addresses:
http://jsoneditor.net/
http://jsonlint.com/

How to get results of a web service ?

Your application will ask this webservice something, then the service will give response with a json result. Your application should get the results with a reader to read the webservice's output.

In PHP, you can do that with file_get_contents() function.

Here is an example of my php application: readwebservice.php

<?php
$jsonObj = file_get_contents('http://mywebserviceurl.com/?s=myparameter');
$final_res = json_decode($jsonObj, true) ;
var_dump( $final_res );
?>

Leave a Reply

Post Navigation