<?php namespace Lc\ShopBundle\Services ; class CityUtils { function callApi($method, $url, $data = false) { $url = 'https://geo.api.gouv.fr/'.$url ; $curl = curl_init(); switch ($method) { case "POST": curl_setopt($curl, CURLOPT_POST, 1); if ($data) curl_setopt($curl, CURLOPT_POSTFIELDS, $data); break; case "PUT": curl_setopt($curl, CURLOPT_PUT, 1); break; default: if ($data) $url = sprintf("%s?%s", $url, http_build_query($data)); } // Optional Authentication: curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "username:password"); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $result = curl_exec($curl); curl_close($curl); return $result; } public function getZipByCity($city) { $zip = null ; $returnCitiesSearchZip = json_decode($this->callApi('get', 'communes', ['nom' => $city, 'fields' => 'nom,codesPostaux'])) ; if($returnCitiesSearchZip) { foreach($returnCitiesSearchZip as $citySearchZip) { if(strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) { $zip = $citySearchZip->codesPostaux[0] ; } } } return $zip ; } }