【问题标题】:php - send and receive xml documentsphp - 发送和接收 xml 文档
【发布时间】:2011-07-21 16:17:43
【问题描述】:

我正在尝试从同样支持 php 的网络服务器获取一个 xml 文档。 这类似于传统的 Web 服务所做的事情,但我想在 php 中实现它。这甚至可能吗?

更具体地了解我的需求 - 我想将 xml 文档作为请求发送到服务器,让 PHP 对其进行一些处理,然后将 xml 文档作为响应发回给我。

提前致谢。

【问题讨论】:

标签: php


【解决方案1】:

也许你只是想要http://php.net/SOAP

如果不是 SOAP,那么您可以发送您的 XML POST 请求并使用 $xml = file_get_contents('php://input'); 将其转储到您可以提供给 http://php.net/DOM 或其他 XML 处理器的变量中。

处理后,你header('Content-Type: text/xml');(或application/xml)并输出修改后的XML文档。

【讨论】:

  • 为什么不使用http_get_request_body 和另一个http_get_request_* family of functions 而不是php://input
  • 因为那些不是标准函数;他们需要一个可能不可用的 PECL 模块。 php://input 无处不在。
  • +1... 确实如此,但除非它是 Intranet,否则它应该不是问题。自 ~2000 年以来,我还没有部署到不允许安装 PECL 扩展或 PEAR 包的主机。
  • 谢谢 Tino,file_get_contents('php://input'); 辛苦了,http_get_request_body 功能在我使用的服务器中不可用。
【解决方案2】:

读取 XML 请求体的超级简单示例:

$request = http_get_request_body();
if($request && strpos($request, '<?xml') !== 0){
   // not XML do somehting appropriate
} else {
  $response = new DomDocment(); // easier to manipulate when *building* xml
  $requestData = DomDocument::load($request);
  // process $requestData however and build the $response XML

  $responseString = $response->saveXML();
  header('HTTP/1.1 200 OK');
  header('Content-type: application/xml');
  header('Content-length: ', strlen($responseString));
  print $responseString;
  exit(0);

}

【讨论】:

  • 我看到服务器报告“调用未定义函数 http_get_request_body()”错误。我正在运行 PHP 版本 5.2.17,我可以访问 phpinfo() 但我不确定需要什么模块才能使服务器停止抱怨找不到 http_get_request_body()。谢谢
  • 您需要pecl_http。或者,您可以按照Tino 的建议用file_get_contents('php://input') 替换该调用
  • 谢谢。但我认为我的托管服务没有安装 pecl_http 模块。我为 pecl 找到的唯一参考是 sqlite。但 file_get_contents API 有效。
【解决方案3】:

使用卷曲。

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xmlString);

//execute post
$result = curl_exec($ch);

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多