Home

Tuesday, August 14, 2012

How to use Curl with json (API)


Step - 1 --> index.php
<?php
  $url = 'http://your_domain_name.com/api.php';
 
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  $result = curl_exec($ch);
  $info = curl_getinfo($ch);
  curl_close($ch);
  $data = json_decode($result, true);
  echo "<pre>";
  print_r($data);
  echo "</pre>";
?>

Step - 2 --> api.php

<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("medical",$con) or die("database Error".mysql_error());

$aData = getAll();

if (count($aData))
 {
echo json_encode(array('data' => $aData));
} else {
echo json_encode(array('data' => 'Nothing found'));
}

 function getAll()
 {
        $query = "SELECT * FROM user";
if (! $query)
            return array();

        $res = mysql_query($query) or die("Query Error".mysql_error());
        $arr_res = array();
        if ($res) {
            while ($row = mysql_fetch_assoc($res))
                $arr_res[] = $row;
            mysql_free_result($res);
        }
        return $arr_res;
 }
?>

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth