2011-10-04 97 views
0

我想向php开发人员解释如何使用我们的Web服务。有一点语言障碍,但本质上它是通过将xml数据直接发布到url来工作的。这是你如何在C#中完成的,它工作的很好;如何在PHP中使用xml(使用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直接发布到我给他们的网址上,其中大约80%会直接发送,其他20%会让人困惑!)。有人能给我一个更好的解释,让更多的人可以理解吗?

+0

这将帮助:http://stackoverflow.com/questions/3898294/make-a-post-request – SuperSaiyan

+0

这是在PHP蠕虫打开一个插座之类的东西的整体能。他应该尽量用卷发来做。看到这里:http://davidwalsh.name/execute-http-post-php-curl – albertjan

+0

是的,他说他试图使用卷曲,但他无法得到它的工作。我已经为他搜索了它,并要求他尝试一些代码,但我不是一个真正的PHP开发人员,所以它非常受欢迎,并希望! –

回答

1

希望这有助于是什么。

<?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(); 
}