Search code examples
phpweb-servicescurlasmx

php - using curl to consume this web service


I saw this post on consuming a web service using CURL: Consume WebService with php

and I was trying to follow it, but haven't had luck. I uploaded a photo of the web service I'm trying to access. How would I formulate my request given the example below, assuming the URL was:

https://site.com/Spark/SparkService.asmx?op=InsertConsumer

enter image description here

I attempted this, but it just returns a blank page:

 $url = 'https://xxx.com/Spark/SparkService.asmx?op=InsertConsumer?NameFirst=Joe&NameLast=Schmoe&PostalCode=55555&[email protected]&SurveyQuestionId=76&SurveyQuestionResponseId=1139';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);

    $xmlobj = simplexml_load_string($result);
    print_r($xmlobj);

Solution

  • Really, you should probably look at the SOAP extension. If it is not available or for some reason you must use cURL, here is a basic framework:

    <?php
    
      // The URL to POST to
      $url = "http://www.mysoapservice.com/";
    
      // The value for the SOAPAction: header
      $action = "My.Soap.Action";
    
      // Get the SOAP data into a string, I am using HEREDOC syntax
      // but how you do this is irrelevant, the point is just get the
      // body of the request into a string
      $mySOAP = <<<EOD
    <?xml version="1.0" encoding="utf-8" ?>
    <soap:Envelope>
      <!-- SOAP goes here, irrelevant so wont bother writing it out -->
    </soap:Envelope>
    EOD;
    
      // The HTTP headers for the request (based on image above)
      $headers = array(
        'Content-Type: text/xml; charset=utf-8',
        'Content-Length: '.strlen($mySOAP),
        'SOAPAction: '.$action
      );
    
      // Build the cURL session
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_POST, TRUE);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $mySOAP);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    
      // Send the request and check the response
      if (($result = curl_exec($ch)) === FALSE) {
        die('cURL error: '.curl_error($ch)."<br />\n");
      } else {
        echo "Success!<br />\n";
      }
      curl_close($ch);
    
      // Handle the response from a successful request
      $xmlobj = simplexml_load_string($result);
      var_dump($xmlobj);
    
    ?>