Convert terminal cURL command to PHP cURL request

2019-09-06 02:58发布

问题:

I am trying to send a cURL request from PHP to Here Maps' RESTFUL Batch API.

The documentation states, that using this cURL script, I can send a data file with the data I need to them:

curl -X POST -H "Content-Type: text/plain" --data-binary @addresses.txt
            "http://batch.geocoder.cit.api.here.com/6.2/jobs?
         &app_code=AJKnXv84fjrb0KIHawS0Tg
         &app_id=DemoAppId01082013GAL
         &action=run
         &header=true
         &inDelim=;
         &outDelim=,
         &outCols=recId,latitude,longitude,locationLabel
         &mailto=<my_email>
         &outputcombined=true
         &language=de-DE"

I am trying to convert this to PHP. I came up with the following code:

$cURLHandler = curl_init();
$url = "http://batch.geocoder.cit.api.here.com/6.2/jobs?&app_code=AJKnXv84fjrb0KIHawS0Tg&app_id=DemoAppId01082013GAL&action=run&mailto=trisztanthar@mailinator.com&outCols=recId,latitude,longitude,locationLabel&outputcombined=true&inDelim=;&outDelim=;";
if($cURLHandler) {
    curl_setopt($cURLHandler, CURLOPT_HTTPHEADER, array('Content-Type: text/plain')); 
    curl_setopt($cURLHandler, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($cURLHandler, CURLOPT_POST, 1);
    curl_setopt($cURLHandler, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, array('addresses' => new CurlFile("./batchjob.txt", 'text/plain', "batchjob.txt")));
    curl_setopt($cURLHandler, CURLOPT_URL, $url);
    curl_exec($cURLHandler);
    curl_close($cURLHandler);
}
else {
    throw new RuntimeException("Nem sikerült felvenni a kapcsolatot egy távoli szerverrel.");
}

When using it, I get the following error:

Only pipe (|), semicolon (;), colon (:), tab (' ') and comma (,) delimiters allowed.

First I thought, that there was a problem with the file, however I tried to run the terminal command in a unix terminal with the same file I tried to use with PHP, and it went through without any problems, responded with a proper response, so its 100% that the PHP code I'm using isn't posting the file.

I'm currently developing on localhost, with MAMP Server (OSX). The batchFile.txt file is in the /Applications/Mamp/htdocs/php/ folder (localhost/php/batchfile.txt).

What am I doing wrong?

回答1:

From your commandline you are directly posting the file as binary data. So send the content like below.

curl_setopt($cURLHandler, CURLOPT_POSTFIELDS, file_get_contents("batchjob.txt"));