Montaser Qasem Montaser Qasem - 2 months ago 18
HTTP Question

Sending XML object request in PHP

I have a PHP code to send a POST request with an XML object to server , but it doesn't work and i think the problem is with the request i looked up for a questions like that and i tried to do what they proposed but still doesn't work.
here's my PHP code:

$url = 'http://example/service.asmx';
$xml='<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Get_schadual xmlns="http://tempuri.org/">
<User>exmaple</User>
</Get_schadual>
</soap:Body>
</soap:Envelope>';
$post_data = array('xml' => $xml);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n X-Requested-With: XmlHttpRequest",
'method' => 'POST',
'content' => http_build_query($post_data)));
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

Answer

I recommend you use cURL for that. The following example should accomplish what you're trying to do:

$xml = "<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
<Get_schadual xmlns="http://tempuri.org/">
<User>exmaple</User>
</Get_schadual>
</soap:Body>
</soap:Envelope>";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://example/service.asmx");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);

$result = curl_exec($ch);
curl_close($ch);

var_dump($result);
Comments