将json数据发布到API方法

时间:2015-03-25 07:51:13

标签: php json api post

有人可以检查我的代码是否正确包含这些行吗?

$headers= array('Accept: application/json','Content-Type: application/json'); 

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

你能检查我的这段代码是否有用吗?

<?php
$data = array(
             "Name" =>"Your Name Here",
             "ContactNumber" =>"+6390000000",
             "IncidentNature" =>"Disaster",
             "IncidentType" =>"Fire",
             "Facts" =>"Some Facts Here",
             "Location" =>"Location of Incidnet",
             "XCoordinate" =>"145.1523",
             "YCoordinate" =>"89.2542",
            "DateOfIncident" =>"2015-03-23T10:01:00"
         );

 $url_send ="http://my.websiteaddress.com/api/Controller/Action";
 $str_data = json_encode($data);

 function sendPostData($url, $post){
      // I put here the added code
     $headers= array('Accept: application/json','Content-Type:application/json');

     $ch = curl_init($url);

      // I put here the added code
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
     $result = curl_exec($ch);
     curl_close($ch);  // Seems like good practice

     return $result;
   }

 echo " " . sendPostData($url_send, $str_data);

?>

0 个答案:

没有答案