Let's make a webservice in php

It's easy to create web service in php.

First create one php file in your website folder like "firstwebservice.php".
and open this file in any text editor.

Now copy this code and past in file.

<?php
//add header for json
header("Content-Type:application/json");

//if you send url paramers
if(!empty($_REQUEST))
    {
        //url parameter "param"
        if(isset($_REQUEST["param"]))
        {
            try
            {
                $param=$_REQUEST['param'];  
              
                $response['status'] = 200;
                $response['param'] = $param;
              
                //return output as json format
                echo json_encode($response);
            }
            catch(Exception $ex)
            {
                $error = array(
                    "status"=> 500,
                    "message"=>".$ex->getMessage()."
                );
                echo json_encode($error);
            }
        }
    }

?>
Now open your web browser and link your website.at last type your file name and set parameter.
Like
**Your website like**/firstwebservice.php?param=this is test
Output of this code is :
{"status":200,"param":"this is test"}
Try on your side and chanege param , use database connection and  get data in json.

Thank you for read this.
Enjoy learning.(;

Comments

Popular posts from this blog

How to set self page in form action?