Custom API and cunsuming in php?



PHP Snippet 1:

<?php
$books = array(
    "java"=>"222",
    "php"=>"333",
    "c"=>"111",
    "AngularJS"=>"111"
);

return json_encode($books);

PHP Snippet 2:

$books = json_decode($books_json);

PHP Snippet 3:

ex:API: http://www.customapi.com/java
   Client URI: http://www.clientcustomapi.com/

PHP Snippet 4:

header("Content-Type: application/json;charset=utf-8");
include('functions.php');
//process client request
if(!empty($_GET['name'])){
    $name = $_GET['name'];
    $price = get_price($name);
    if(empty($price)){
        //book not found
        deliveryResponse(200,"Book not found",NULL);
    }else{
        //response book price
        deliveryResponse(200,"Book found",$price);
    }
}else{
    //invalid request
    deliveryResponse(400,"invalid Request",NULL);
}

PHP Snippet 5:

function get_price($find){
    $books = array(
        "java"=>"222",
        "php"=>"333",
        "c"=>"111"
        );
    foreach ($books as $book => $price) {
        # code...
        if($book==$find){
            return $price;
            break;
        }
    }

}
function deliveryResponse($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;
}

PHP Snippet 6:

<!DOCTYPE html>
<html>
<head>
    <title>Book Price</title>
</head>
<body>
<form method="post" action="" name="bookprice">
    <label>Book Name:</label><input type="text" name="book" id="book">
    <input type="submit" value="submit" name="submit">
</form>
</body>
</html>
<?php 
if (isset($_POST['submit'])) {
    //simple Request
    $name = $_POST['book'];
    //resource address
    $url ="http://www.customapi.com/$name";

    //send request to resource
    $client = curl_init($url);
    curl_setopt($client,CURLOPT_RETURNTRANSFER, 1);
    //get response from resource
    $response = curl_exec($client);
    $result = json_decode($response);
    if($result->data !=null){
        echo $result->data;
    }else{
        echo"No record found";
    }


}
?>