Kod*_*Kid 4 php xml rest post http
我是REST Web服务的新手.我需要使用php将一些信息发布到REST Web服务,并使用响应为用户提供产品(响应是产品的代码).我的任务:1)HTTP方法是帖子2)请求主体是XML 3)标题需要有一个API密钥ex:some-co-APIkey:4325hlkjh 4)响应是xml,需要进行解析.我的主要问题是如何设置标题以使其包含密钥,如何设置正文以及如何获取响应.我不确定从哪里开始.我敢肯定这很简单但是因为我从未见过它,所以我不知道如何处理这个问题.如果有人能告诉我一个很棒的例子.在此先感谢您的帮助.
我在想这样的事情;
$url = 'webservice.somesite.com';
$xml = '<?xml version="1.0" encoding="UTF-8"?>
<codes sku="5555-55" />';
$apiKey = '12345';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
## For xml, change the content-type.
curl_setopt ($ch, CURLOPT_HTTPHEADER, $apiKey);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
if(CurlHelper::checkHttpsURL($url)) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
}
// Send to remote and return data to caller.
$result = curl_exec($ch);
curl_close($ch);
Run Code Online (Sandbox Code Playgroud)
这看起来是对的吗?
您应该使用cURL.你应该阅读文档,但这是我写的一个函数,可以帮助你.根据您的目的修改它
function curl_request($url, $postdata = false) //single custom cURL request.
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
if ($postdata)
{
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
}
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Run Code Online (Sandbox Code Playgroud)
至于XML,php有一些很好的解析它的功能.查看simplexml.
| 归档时间: |
|
| 查看次数: |
12535 次 |
| 最近记录: |