Showing posts with label API. Show all posts
Showing posts with label API. Show all posts

Wednesday, May 7, 2014

How to create API with Json as output

Hi,Friends

How to create a API in PHP which gives a json output

First of all json is very light and secured way of getting data from an API. we will make an API to output a json

Here is a simple example

File: index.php

<?php
 $url = 'http://localhost/jsonapi/json.php';//url for json
 
 include('connect.php');//db connnection
 
 $query = "SELECT * FROM category";

$result = mysql_query($query) or die("Query failed");
  
       while ($row = mysql_fetch_array($result)) {
          $record[]=array($row["id"],$row["categoryname"]);
     }
 //curl for secured transaction of data

   $ch=curl_init($url);
    $data_string = urlencode(json_encode($record));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, array("category"=>$data));


    $result = curl_exec($ch);
    curl_close($ch);

   // echo $result;
?>


File: json.php

<?php
$data = $_POST['category'];
$output_data = ( urldecode( $datastring));
print_r($output_data);
?>
Function mainly used is json_encode

Now just run these file and you will get a json output for your API

just simple as that!!!!!!!!