Tuesday, 1 April 2014

How to make API in PHP and getting JSON object in response.

Here we are using two php file one is index.php and other one is functions.php

index.php  

-----------------------------------------------Starts here------------------------------------------------
<?php


header("Content-Type:application/json");


include("functions.php");



if(!empty($_GET['name']))
{
$name=$_GET['name'];
$price=get_price($name);

if(empty($price))
deliver_response(200,"book not found",NULL);
else
deliver_response(200,"book found",$price);

}
else
{
deliver_response(400,"Invalid Request",NULL);
}
function deliver_response($status,$status_message,$data)
{
header("HTTP/1.1 $status $status_message");

$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;

$json_response=json_encode($response);
echo $json_response;
}

?>

-----------------------------------------------Ends here--------------------------------------------------

functions.php

-----------------------------------------------Starts here------------------------------------------------

<?php

function get_price($find)
{
$books=array(
    "english"=>400,
        "math"=>500,
        "science=>600"
    
    );
    
    foreach($books as $book=>$price)
    {
    if($book==$find)
{
return $price;
break;
}
    }

}

?>
-----------------------------------------------Ends here--------------------------------------------------

Open your browser then open 

localhost?name=english //or your value