Removing unnecessary extra characters from both the beginning and end of a SOAP response when using PHP SoapClient

When I attempted to retrieve data from a SOAP API server using PHP, I encountered an issue with the response code. The code "looks like we got no XML document" was returned.

try {
    $soap = new SoapClient($wsdl, $options);
    $data = $soap->GetXYZ($params);
}
catch(Exception $e) {
    $Lastresponse = $soap->__getLastResponse();
}

Upon inspecting the $Lastresponse variable in the catch block, I found it contained additional information:

------=_Part_1134075_393252946.1482317378966 Content-Type: application/xop+xml; charset=utf-8; type="text/xml" <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> ......all valid data ... </SOAP-ENV:Body> </SOAP-ENV:Envelope> ------=_Part_1134075_393252946.1482317378966--

Note: The $options array I am using includes parameters such as 'uri', 'soap_version', 'cache_wsdl', and more to define the SOAP settings.

Although I managed to handle the XML parsing workaround, I'm curious about the extra -----Part bits in the response. Any insights on what might be causing this or if there's a mistake in my setup?

Answer №1

Those specific markers known as the boundary in multipart messages are described in detail here and defined in RFC2387.

Upon investigation, it appears that SoapClient lacks the ability to interpret multipart messages, leading to the exception you encountered.

The workaround involves extending SoapClient to extract the XML content using regex or other string methods. Here is a sample approach found on this page:

class MySoapClient extends SoapClient {
    public function __doRequest($request, $location, $action, $version, $one_way = 0) { 
        $response = parent::__doRequest($request, $location, $action, $version, $one_way);
        $start = strpos($response,'<?xml'); 
        $end = strrpos($response,'>'); 
        return substr($response,$start,$end-$start+1);
    }
}

Answer №2

Kindly test the query below and share your feedback:


$headers = array(
    "POST: ".url." HTTP/1.1",
    "Host: ".domain."",
    "Accept-Encoding: gzip,deflate",
    "Content-type: text/xml;charset=UTF-8",
    "SOAPAction: \"http://tempuri.org/wsdlurl/methodname\"",
    "Connection: Keep-Alive",
    "Content-length:".strlen($xml),
    "User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
    "
)

$url = your url;
$ch = curl_init();      
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_POSTFIELDS, $options); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);     
$response = curl_exec($ch);
$err = curl_error($ch);
$doc = new DOMDocument();
$doc->loadXML( $response );     
$authKey = $doc->getElementsByTagName( "fieldname" );

Answer №3

Make sure to handle Exceptions:

When using SoapClient in non-WSDL mode, not providing the location and uri options will result in an E_ERROR error being generated.

If the wsdl URI cannot be loaded, a SoapFault exception will be thrown.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing data with Laravel 5.3 using Storage::put and XMLHttpRequest

Attempting to send a file using DRAG & DROP with XMLHttpRequest. $images = $_FILES['images']; When I use foreach: foreach($images["name"] as $file => $name) and move_uploaded_file($images["tmp_name"][$file], $images_dir . $name it works ...

Incorporate Live Data into Google Charts Using Ajax Response for a Dynamic Visualization

I am struggling to successfully load a responsive Google Line Chart after an Ajax call. I have attempted to place the entire Google Chart code within the success part of the Ajax call, but it does not seem to work as expected. Below is my current Ajax code ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...

JavaScript doesn't automatically redirect after receiving a response

Hey there, I'm attempting to implement a redirect upon receiving a response from an ajax request. However, it seems that the windows.href.location doesn't execute the redirect until the PHP background process finishes processing. Check out my cod ...

Mastering Yii2: Implementing Javascript Functions such as onchange() in a View

One of the elements in my project is a checkbox: <div class="checkbox"> <label> <?= Html::checkbox('chocolate', false) ?> Chocolate </label> </div> In addition to that, I also have a span ta ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Utilizing Bootstrap Modal to Display PHP Data Dynamically

Modals always pose a challenge for me, especially when I'm trying to work with someone else's code that has a unique take on modals that I really appreciate (if only I can make it function correctly). The issue arises when the modal is supposed ...

Warning displayed on form input still allows submission

How can I prevent users from inserting certain words in a form on my website? Even though my code detects these words and displays a popup message, the form still submits the data once the user acknowledges the message. The strange behavior has me puzzled. ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

Accessing form data from Ajax/Jquery in php using $_POST variables

Thank you in advance for any assistance on this matter. I'm currently attempting to utilize Ajax to call a script and simultaneously post form data. While everything seems to be working correctly, the $POST data appears to come back blank when trying ...

Unexpected error 500 (Internal Server Error) occurred due to BadMethodCallException

Using Vue 2.0 and Laravel 5.4, I am working on creating a matching system that includes a dynamic Vue component. For example, when someone likes another person, it should immediately show that the like has been sent or if the like is mutual, it should indi ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...