如何在PHP5中接收和处理通过POST请求的XML文件?

时间:2011-02-02 03:27:45

标签: php xml simplexml remote-access

我想在PHP5中使用simeplexml类来处理一个小的XML文件。但是要获取该文件,脚本必须向远程服务器发送特定的POST请求,该服务器将“返回”给我一个XML文件。所以我相信我不能使用“simplexml_load_file”方法。只需要处理这个文件,然后它就可以,甚至应该被删除/删除。 我有这种类型的HTTP HEADER

$header = 'POST '.$gateway.' HTTP/1.0'."\r\n" .
          'Host: '.$server."\r\n".
          'Content-Type: application/x-www-form-urlencoded'."\r\n".
          'Content-Length: '.strlen($param)."\r\n".
          'Connection: close'."\r\n\r\n";

并不知道接下来要做什么。有fsockopen,但我不确定这是否合适或如何使用它。

2 个答案:

答案 0 :(得分:1)

我的建议是使用类似Zend_Http_Client库或cURL的东西。使用fsockopen使一切正确将是一个痛苦的调试。

Zend_Http_Client有一个很好的界面,可以很棒。

CURL也不是太痛苦,并且已经是大多数PHP构建的一部分。 示例如下:

$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/"); // Replace with your URL
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch) // Return the XML string of data

// Parse output to Simple XML
// You'll probably want to do some validation here to validate that the returned output is XML
$xml = simplexml_load_string($output); 

答案 1 :(得分:0)

我会使用像Zend_Http_Client这样的HTTP客户端库(如果你是受虐狂,则使用cURL)来创建POST请求,然后将响应正文提供给simplexml_load_stringSimpleXMLElement::__construct()