Skip to main content

PHP :: How to request Webservice using PHP CURL

I had a problem when requesting webservice. My solution as follows.

        $url = "https://path_to_service.asp";
     //setting the curl parameters. 
     $headers = array("Content-type: text/xml;charset=\"utf-8\"", 
                      "Accept: text/xml",
                      "Cache-Control: no-cache",
                      "Pragma: no-cache",
                      "SOAPAction: \"run\"" 
                     ); 
     try{
         $ch = curl_init(); 
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_POST, 1); 
         // send xml request to a server 
         curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); 
         curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_POSTFIELDS,  $xmlRequest); 
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_VERBOSE, 0); 
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         $data = curl_exec($ch);
         //convert the XML result into array 
         if($data === false){ 
           $error = curl_error($ch);
           echo $error;
           die('error occured'); 
         }else{ 
           $data = json_decode(json_encode(simplexml_load_string($data)), true);                } 
           curl_close($ch);             
         }catch(Exception  $e){ 
           echo 'Message: ' .$e->getMessage();die("Error");       
         }

I think this will be helpful for others.

Comments