如何将这个wget函数转换为php?

时间:2013-03-23 14:11:09

标签: php xml linux wget

wget -d --header="Content-Type:application/xml" --post-data="$(cat <your xml file>)" http://sample.sample.com/api

我如何在PHP中使用此功能? 我也希望得到这个函数的响应。 我在php中有一个变量,就像这样

$xml = '<sample>
    <Request target="test">
    </Request>
</sample>'

这是我要发布的xml。

我尝试了以下内容:

$url = 'sample.sample.com/api';;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$(cat <".$xml.">)"); // receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $server_output = curl_exec ($ch);
curl_close ($ch);

但它返回了这个错误:

  

解析XML失败:期望开始标记,'&lt;'找不到

2 个答案:

答案 0 :(得分:1)

您应该能够遵循Sending and Receiving XML using PHP所示的类似方案。该站点的第二部分(发送XML)使用curl来处理此操作,该操作具有与wget类似的属性,但使用PHP库而不是命令行二进制和参数。我会在网站上加入这段长片。

<?php
  /*
   * XML Sender/Client.
   */
  // Get our XML. You can declare it here or even load a file.
  $xml_builder = '
                  <?xml version="1.0" encoding="utf-8"?>
                  <Test>
                      <String>I like Bharath.co.uk!</String>
                  </Test>
                 ';
  // We send XML via CURL using POST with a http header of text/xml.
  $ch = curl_init('http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_builder);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.bharath..co.uk');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $ch_result = curl_exec($ch);
  curl_close($ch);
  // Print CURL result.
  echo $ch_result;
?>

答案 1 :(得分:0)

我想是的......

$cmd = "wget -d --header=\"Content-Type:application/xml\" --post-data=\"$(cat <your xml file>)\" http://sample.sample.com/api";
exec($cmd);
$outputfile = "dl.html";
echo file_get_contents($outputfile);