在PHP中发送XML对象请求

时间:2016-09-14 16:05:18

标签: php xml http

我有一个PHP代码,用于向服务器发送带有XML对象的POST请求,但它不起作用,我认为问题出在请求我查找了类似的问题,我试图做他们做的事情建议但仍然无效。 这是我的PHP代码:

$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);

1 个答案:

答案 0 :(得分:0)

我建议您使用cURL。以下示例应该完成您要执行的操作:

$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);