【问题标题】:Send xml to webservices using Curl in PHP but returns error在 PHP 中使用 Curl 将 xml 发送到 web 服务但返回错误
【发布时间】:2012-01-05 12:11:24
【问题描述】:

我有一个 Web 服务,我向它发送一个 xml 请求(应用程序/x-www-form-urlencoded 编码)并得到响应。 这些被发送到包含在名为“xml”的查询参数中的 URL

当我使用如下所示的简单 html 表单时,我会返回一个结果。但是,当我使用我的 php 代码时,我返回了一个错误。也许是因为这个:这些被发送到包含在名为“xml”的查询参数中的 URL?如果是这种情况,我如何在该参数中发送它?如果有人能指出我做错了什么,我将不胜感激。非常感谢

<form method="post" name="form1" action="http://webservicesapi.com/login.pl">
  <textarea cols="80" rows="20" name="xml">
      <?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>
  </textarea>

<input type="submit" value="submit XML document">
</form>

这不起作用:

<?php
// open a http channel, transmit data and return received buffer
function xml_post($xml, $url, $port)
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];

$ch = curl_init();    // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1);              // Fail on errors

if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port);          //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
}

$data = curl_exec($ch);

curl_close($ch);

return $data;
}

$xml = '<?xml version="1.0"?><request><auth username="hello" password="world" /><method action="login" /></request>';

$url ='http://webservicesapi.com/login.pl';
$port = 80;
$response = xml_post($xml, $url, $port);    
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>
<body>
<P><?=nl2br(htmlentities($response));?></P>
</body>
</html>
?>

【问题讨论】:

  • 你可能想发布你的错误。

标签: php xml web-services curl


【解决方案1】:

CURLOPT_POSTFIELDS 需要关联数组或原始帖子字符串。由于您将其传递给字符串,因此它将其视为原始帖子字符串。因此,其中任何一个都应该起作用:

$response = xml_post(array('xml' => $xml), $url, $port);  

$response = xml_post('xml='.urlencode($xml), $url, $port);  

【讨论】:

    猜你喜欢
    • 2015-06-16
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 2011-05-05
    • 2010-11-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多