使用PHP发送XML数据的HTTP POST请求

24

我需要发送这个XML

      <?xml version="1.0" encoding="UTF-8"?>
<gate>
   <country>NO</country>
   <accessNumber>1900</accessNumber>
   <senderNumber>1900</senderNumber>
   <targetNumber>4792267523</targetNumber>
   <price>0</price>
   <sms>
      <content><![CDATA[This is a test æøå ÆØÅ]]></content>
   </sms>
</gate>

我想把一条短信发送到短信网关服务。该服务监听HTTP POST请求,XML必须嵌入在POST请求的BODY中。

我正在使用PHP和CodeIgniter框架,但我对PHP完全不了解,因此最好能有一个详细的指南,但是任何指向正确方向的指针都将不胜感激。

2个回答

33

你可以使用cURL库来发布数据: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

如果postfield包含你需要发送的XML数据,你需要将postfield命名为API服务(我猜是Clickatell)所期望的名称。


是啊,我希望......我问了IT人员是否可以安装cURL,但是他无法在合理的时间内完成。 - Frode
5
请参考此博客文章:http://netevil.org/blog/2006/nov/http-post-from-php-without-curl 。 - dusoft
还有强大而非常好用的pecl_http扩展和各种PEAR HTTP_*包(更容易让你的IT人员安装)。 - GZipp
@dusoft - 感谢您提供netevil.org的链接。 - GZipp

23

另一种选项是使用file_get_contents()函数:

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

是的,流在PHP 4.3中已经被引入,但对于大多数用户来说仍然相当隐蔽。 - dusoft
我遇到了错误:{警告:file_get_contents(http://www.nwmls.com/Schemas/General/EverNetQueryXML.xsd)[function.file-get-contents]:无法打开流:HTTP请求失败! HTTP / 1.1 404未找到,位于/home/phretscl/public_html/xml/pulldata.php的第42行}。 - Neocortex
1
等一下,问题不是“我如何发送XML”,而是“我如何接收XML并读取它”吗? - ChristoKiwi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接