如何在php中POST xml (c#示例)

本文关键字:示例 xml POST php | 更新日期: 2023-09-27 18:10:18

我试图向php开发人员解释如何使用我们的web服务。有一点语言障碍,但本质上它是通过将xml数据直接发送到url来工作的。下面是你如何在c#中完成它,它工作得很好;

public string POSTXml(string xml, string url)
{
    WebRequest req = null;
    WebResponse rsp = null;
    try
    {
        StringBuilder strRequest = new StringBuilder();                       
        req = WebRequest.Create(url);
        req.Method = "POST";        
        req.ContentType = "text/xml";     
        StreamWriter writer = new StreamWriter(req.GetRequestStream());
        writer.WriteLine(xml);
        writer.Close();
        rsp = req.GetResponse();
        var sr = new StreamReader(rsp.GetResponseStream());
        string responseText = sr.ReadToEnd();
        return responseText;
    }
    catch (Exception e)
    {
        throw new Exception("There was a problem sending the message");
    }
}

开发人员在php中执行此操作时遇到麻烦。有人能把上面的代码翻译成php吗?

同样,我从我的前任那里继承了这段代码,如果我诚实的话,我从来没有见过这样实现的web服务…我开始担心是我没有很好地解释它(我只是告诉人们直接将xml发送到我给他们的url,大约80%的人直接得到了它,另外20%的人感到困惑!)。有没有人能给我一个更好的解释,让更多人明白?

如何在php中POST xml (c#示例)

希望这对你有帮助。

<?php
// Some code borrowed from http://www.php.net/manual/en/function.curl-exec.php
$url = 'http://www.example.com/';
$xml = '<?xml version="1.0"?><data>x</data>';
try
{
    $ch = curl_init();
    // set URL and other appropriate options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
    curl_exec($ch);
    if (curl_errno($ch))
    {
        throw new Exception(curl_errno($ch) . ': ' . curl_error($ch));
    }
    else
    {
        $result = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($returnCode == 404)
        {
            throw new Exception('URL Invalid');
        }
    }
    curl_close($ch);
    echo $result;
}
catch (Exception $exception)
{
    echo '[Error Message] ' . $exception->getMessage();
}

这个怎么样:

http://www.codediesel.com/php/posting-xml-from-php/

使用了CURL,所以应该和后面的内容保持一致