dscdttg4389 2013-06-06 17:48
浏览 25
已采纳

在PHP中复制命令行cURL

I'm integrating with a 3rd party's API, I have to POST some XML and I get some XML back.

On the CLI this works, I get a positive response.

curl -X POST -d @/tmp/file http://url/to/endpoint --header "Content-Type:application/x-www-form-urlencoded"

This, however, does not work, the response contains an error telling me my that my request XML is invalid.

$ch = curl_init();

$post = array(
  'file' => '@/tmp/file'
);

curl_setopt($ch, CURLOPT_URL,             'http://url/to/endpoint');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,  true);
curl_setopt($ch, CURLOPT_POST,            true);
curl_setopt($ch, CURLOPT_HTTPHEADER,      array('Content-type:application/x-www-form-urlencoded'));

curl_setopt($ch, CURLOPT_POSTFIELDS,      $post);

$this->responseBody = curl_exec($ch);

curl_close($ch);

It's the same file in both cases and it's on the same server. the file is just plain text XML. The only difference that I can see is that I'm specifying a fieldname in my HTTP headers on the PHP version.

How do I send that file over using PHP to exactly replicate the CLI version, e.g. without the formdata/fieldname bit?

FWIW I can't go back to the developer of the API for a few days to ask what he's defining as 'bad XML'

  • 写回答

1条回答 默认 最新

  • dongya6997 2013-06-06 18:25
    关注

    Try passing the file as raw data, not in an array, by for example using file_get_contents().

    So instead of:

    $post = array('file' => '@/tmp/file');
    

    Like this:

    $post = file_get_contents('@/tmp/file');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像