ARTICLE AD BOX
I am using a curl request for my backend php class to access google's computeRoute.
when I run a curl request with a string it works (as below).
However dynamically generate the values with an array and then convert to an object i get the error message;
"Object of class stdClass could not be converted to string"
Code Example:
This works:
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://routes.googleapis.com/directions/v2:computeRoutes', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS =>'{ "origin":{ "location":{ "latLng":{ "latitude": 37.419734, "longitude": -122.0827784 } } }, "destination":{ "location":{ "latLng":{ "latitude": 37.417670, "longitude": -122.079595 } } }, "travelMode": "DRIVE", "routingPreference": "TRAFFIC_AWARE", "computeAlternativeRoutes": false, "routeModifiers": { "avoidTolls": false, "avoidHighways": false, "avoidFerries": false }, "languageCode": "en-US", "units": "METRIC" }', CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'X-Goog-Api-Key: myPrivateKey', 'X-Goog-FieldMask: *' ), )); $res = curl_exec($curl); curl_close($curl); DD($res);However, when i try the same with dynamically generated array it produced an error:
Example of Error:
$curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => 'https://routes.googleapis.com/directions/v2:computeRoutes', CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => json_decode(json_encode($this->converToObjects())), CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', 'X-Goog-Api-Key: myPrivateKey', 'X-Goog-FieldMask: *' ), )); $res = curl_exec($curl); curl_close($curl);The array:
public function converToObjects() { return [ 'origin' => [ 'location' => [ 'latLng' => [ 'latitude' => 37.419734, 'longitude' => -122.0827784 ] ] ], 'destination' => [ 'location' => [ 'latLng' => [ 'latitude' => 37.41767, 'longitude' => -122.079595 ] ] ], 'travelMode' => 'DRIVE', 'routingPreference' => 'TRAFFIC_AWARE', 'computeAlternativeRoutes' => false, 'routeModifiers' => [ 'avoidTolls' => false, 'avoidHighways' => false, 'avoidFerries' => false ], 'languageCode' => 'en-US', 'units' => 'METRIC' ]; }Why does it work with my parameter being hard-coded but fail if I pass the array dynamically?
