Jorl17 / open-elevation

A free and open-source alternative to Google Elevation API. Host your own! https://open-elevation.com
GNU General Public License v2.0
689 stars 167 forks source link

PHP: Send POST request #49

Closed vsevjednom-cz closed 3 years ago

vsevjednom-cz commented 3 years ago

Hi, I'm trying to send POST request but without success. I'm getting this error: Invalid JSON.

Request in bash works ok:

curl -X POST   https://api.open-elevation.com/api/v1/lookup   -H 'Accept: application/json'   -H 'Content-Type: application/json'   -d '{"locations":[{"latitude":49.166451,"longitude":16.576265},{"latitude":49.166443,"longitude":16.576166}]}'
{"results": [{"latitude": 49.166451, "longitude": 16.576265, "elevation": 231}, {"latitude": 49.166443, "longitude": 16.576166, "elevation": 231}]}

But PHP:

$url = 'https://api.open-elevation.com/api/v1/lookup';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Accept: application/json\r\nContent-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"locations":[{"latitude":49.166451,"longitude":16.576265},{"latitude":49.166443,"longitude":16.576166}]}');

Invalid JSON 🤪

How should I edit the source code?

vsevjednom-cz commented 3 years ago

I've got a solution after hours and hours. CURLOPT_HTTPHEADER must contains only Content-Type: application/json and CURLOPT_POST must be false.

Full code:

$url = 'https://api.open-elevation.com/api/v1/lookup';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, '{"locations":[{"latitude":49.166451,"longitude":16.576265},{"latitude":49.166443,"longitude":16.576166}]}');