没有您的其余代码,我只能向您展示我使用表单收集地址所做的工作。将 php 7 与 json_decode() 一起使用。有一种更有效的方法可以做到这一点,但它对我有用。希望这会有所帮助。
//create string holding address to run through google geolocation API for Lat/Long
//make sure to clean your posts, I use functions from another page that cleans htmls tags, trims and removes slashes and/or runs through a reg ex to replace and/or remove unwanted entries for the particular fields type.
$address = clean_post($_POST['cust_street']).' '.clean_post($_POST['cust_city']).' '.clean_post($_POST['cust_state']).', '.clean_post($_POST['cust_zip']);
// Get JSON results from this request
$url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($address).'&sensor=false&key='.APIKEY;
$geo = file_get_contents($url);
// Convert the JSON to an array
$geo = json_decode($geo, true);
if ($geo['status'] == 'OK') {
// Get Lat & Long
$latitude = $geo['results'][0]['geometry']['location']['lat'];
$longitude = $geo['results'][0]['geometry']['location']['lng'];
}else{
$latitude = NULL;
$longitude = NULL;
$sessData['status']['type'] = 'alert alert-warning';
$sessData['status']['msg'] = 'Sorry, but it seems the address you entered is not being recognized by Google Maps API service.';
//die or exit, do something on failure
}
然后您可以将这些变量添加到您的数据库插入/更新和/或根据需要回显它们。这段代码是通过我正在处理的一个小程序运行的,该小程序将给定地址输入到客户表单中,然后处理该地址,获取纬度和经度,然后在成功后,将其放入我正在运行的数组中插入到我的D B。然后,我可以调用它,以便日后在地图上找到经纬度的客户。
$custData = array(
'users_id' => $usr_id,
'cust_first_name' => clean_post( $cust_first_name ),
'cust_last_name' => clean_post( $cust_last_name ),
'cust_email' => clean_email( $cust_email ),
'cust_street' => clean_post( $cust_street ),
'cust_city' => clean_post( $cust_city ),
'cust_state' => clean_post( $cust_state ),
'cust_zip' => clean_post( $cust_zip ),
'cust_phone1' => clean_phone( $cust_phone2 ),
'cust_lat' => clean_phone( $latitude ),
'cust_long' => clean_float( $longitude ),
//etc,etc,etc
);
//$cust = new User(); further up in page
//insertCust() function comes from user class stored in class.user.php
$insert = $cust->insertCust($custData);
//set status based on data insert
if($insert){
//set some session variables and store them before any header redirects.
$_SESSION['status']['type'] = 'alert alert-success';
$_SESSION['status']['msg'] = 'You have registered '.$custName.' successfully!';
}
顺便说一句,我目前正在阅读这份关于 XSS 安全性的文档,发现它对我最有帮助:XSS_Filter_Evasion_Cheat_Sheet
希望这可以帮助。