使用 HTTP POST 和 PHP 发送 XML 数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1660983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:25:52  来源:igfitidea点击:

Sending XML data using HTTP POST with PHP

phpxmlhttpcodeigniterpost

提问by Frode

I need to send this XML

我需要发送这个 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>

to a SMS gateway service. The service listens for HTTP POST requests. The XML must be embedded in the BODY of the POST request.

到 SMS 网关服务。该服务侦听 HTTP POST 请求。XML 必须嵌入在 POST 请求的 BODY 中。

I'm using PHP and the CodeIgniter framework, but I'm a total PHP n00b, so ideally I'd need a thorough guide, but any pointers in the right direction would be appreciated.

我正在使用 PHP 和 CodeIgniter 框架,但我完全是 PHP n00b,所以理想情况下我需要一个全面的指南,但任何指向正确方向的指针都将不胜感激。

回答by dusoft

you can use cURL library for posting data: http://www.php.net/curl

您可以使用 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);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

其中 postfield 包含您需要发送的 XML - 您需要命名 API 服务(我猜是 Clickatell)期望的 postfield

回答by GZipp

Another option would be file_get_contents():

另一种选择是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);