使用 CURL 向 Web 服务器发送 XML 发布请求

2022-08-30 23:11:09

我正在尝试使用php和curl向Web服务器发送请求。我以前没有做过这样的事情,尽管网上有很多很好的例子,但我在理解一些curl命令时遇到了一些困难。

这就是我想做的:有一个已建立的Web服务(例如:Web地图服务),我希望我的php代码向此服务发送post XML请求。作为响应,我想获取一个 XML 文件。

这就是我到目前为止所拥有的:

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ''); 
    /*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, '');*/
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ch_result = curl_exec($ch);
    curl_close($ch);
    echo $ch_result;

正如我所说,我在php和使用curl方面都很陌生,我认为我错过了一些概念。我的问题是:1)我必须放入的字符串(链接)是什么:

          curl_setopt($ch, CURLOPT_URL, ''); 

是我要发送请求的服务主机名吗?

2) 在第 6 行中,变量 $xml 包含我要作为请求发送的 xml 文件。它是正确的,还是这个变量应该包含其他东西?

3)在哪些情况下我需要使用httpheader或header(row3和row4);

感谢您的帮助。迪米特里斯


答案 1

试试这个方法:

  $url = 'https://android.googleapis.com/gcm/send';
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  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>here</xml>" );
  $result = curl_exec($ch);
  curl_close($ch);

欲了解更多详情,请访问: http://php.net/manual/en/function.curl-setopt.php


答案 2

我认为使用HTTP类可能更适合发出HTTP请求。

请参阅 http://www.php.net/manual/intro.http.php

此外,还有针对 PHP 的特定 WMS 库,例如 http://docs.huihoo.com/geoserver/1.6.0/Parsing%20and%20using%20WMS%20capabilities%20with%20PHP.html


推荐