在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'

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');