如何使用cURL与php获取服务器的响应?

时间:2013-01-17 23:41:48

标签: php xml curl response

我有一个发件人脚本和一个接收器脚本。发件人发送一个xml文件,而接收者获取它并将其存储在数据库中。

发件人看起来像这样:

$xml = file_get_contents("data.xml");

  // We send XML via CURL using POST with a http header of text/xml.
  $ch = curl_init();
  // set URL and other appropriate options
  curl_setopt($ch, CURLOPT_URL, "http://localhost/iPM/receiver.php");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt($ch, CURLOPT_REFERER, 'http://localhost/iPM/receiver.php');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $ch_result = curl_exec($ch);
  echo "Result = ".$ch_result;
  curl_close($ch);

和接收者:

$xml = file_get_contents('php://input');

parsing the xml - storing to database
etc etc etc etc etc etc etc etc etc

我需要在运行发件人脚本时,从接收器回复一切正常并收到xml文件的响应。我相信我会看到这行代码,在我的代码中:echo "Result = ".$ch_result;但我看到的唯一内容是Result =

那么我做错了什么?我应该在发送者/接收者身上添加什么来回复?

1 个答案:

答案 0 :(得分:0)

替换以下行:

$ch_result = curl_exec($ch);
echo "Result = " . $ch_result;

使用以下行并查看它是否有效:

$ch_result = curl_exec($ch);
$ch_header = curl_getinfo($ch);
echo "Status : " . $ch_header['http_code'] . "<br />";
echo "Result = " . $ch_result;

curl_getinfo返回有关请求和http_code变量的基本信息,返回响应代码200,404等。然后,您可以检查代码并根据您的要求对其进行解析。

希望它有所帮助。