我找不到checkText函数中if语句的方法,检查城市是否无效,例如:
如果您输入“jfeaio”或任何其他与城市名称不匹配的文字 然后它会说“输入一个有效的城市”。
我在函数中创建了一个if语句,检查输入文本是否为“notkoko”,如果是,那么它将回显“输入一个有效的城市”只是为了测试,它似乎工作,但我想要它可以说每当你输入一个不是城市名或国名的东西时。
我尝试了两件事:
使用get_headers, 检查文件()是否为假。
这两件事确实有效但是,无论如何都会弹出错误,比如我输入了有效的城市名称。
这是网站
http://79.170.40.39/senixmenix.com/PHP/WeatherScraper/index.php
如果您不想访问链接
,这是两个文件的代码scraper.php(这是包含所有PHP的内容)
<?php
$cityTextt = $_GET['city'];
$result = "";
$cityTextt = str_replace(' ', '-', $cityTextt);
$weather = file('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
$result = $weather[353];
$headers = "";
/*if($headers[0] == "HTTP/1.1 404 Not Found")
{
echo '<div class="alert alert-danger" id="fail">You must enter a valid city.</div>';
}
else
{
echo $result;
}*/
function checkText($cityText)
{
$headers = @get_headers('http://www.weather-forecast.com/locations/'.$cityTextt.'/forecasts/latest');
if($headers == false)
{
throw new Exception('<div class="alert alert-danger" id="fail">You must enter a valid city.</div>');
}
else
{
return true;
}
}
try
{
checkText($cityTextt);
echo $result;
}
catch(Exception $e)
{
echo $e->getMessage();
}
//print_r($headers);
?>
这里是index.php(这个不包含任何PHP)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Jesper's Website</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<style type="text/css">
body{
font-family: Copperplate Gothic Light, sans-serif;
}
.large{
font-size: 1000%;
}
.center{
text-align: center;
}
.bold{
font-weight: bold;
}
.marginTop{
margin-top: 30px;
}
.marginRight{
margin-right: 25px;
}
.title{
margin-top: 60px;
font-size: 350%;
}
.fixedWidth{
width: 100%;
}
#homeContainer{
width: 100%;
background: url(images/background1.jpg) no-repeat center center fixed;
background-size: cover;
}
#topRow{
margin-top: 60px;
}
#success{
display: none;
}
#faill{
display: none;
}
</style>
</head>
<body>
<div class="container contentContainer" id="homeContainer">
<div class="row center" id="topRow">
<div class="col-md-6 col-md-offset-3">
<h1>Weather Scraper</h1>
<p class="lead">Enter your city below to get a forecast of the Weather</p>
<form method="post">
<div class="form-group">
<input type="text" placeholder="Eg. Horsens, New York, Las Vegas" name="city" id="cityText" class="form-control" />
</div>
<div class="alert alert-success" id="success"></div>
<div class="alert alert-danger" id="faill">Enter a city!</div>
<input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" id="submitBtn" />
</form>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var cityInput = "";
var wHeight = $(window).height();
$(".contentContainer").css("height", wHeight + "px");
$("#submitBtn").click(function(event){
$(".alert").hide();
cityInput = $("#cityText").val();
event.preventDefault();
if(cityInput != "")
{
$.get("scraper.php?city=" + cityInput, function(data){
if(data == "")
{
$("#faill").html("Enter a valid city!").slideDown(500);
}
else
{
$("#success").html(data).slideDown(500);
}
});
}
else
{
$("#faill").slideDown(500);
}
});
</script>
</body>
</html>
谢谢: - )
答案 0 :(得分:2)
get_headers将返回一个标头数组。在元素[0]中,您将找到返回码:
http://www.weather-forecast.com/locations/San-Diego/forecasts/latest
HTTP/1.1 200 OK
http://www.weather-forecast.com/locations/san-diego/forecasts/latest
HTTP/1.1 301 Moved Permanently
http://www.weather-forecast.com/locations/san diego/forecasts/latest
HTTP/1.1 404 Not Found
如果请求失败,它只返回false,例如没有来自服务器的响应。 因此,您必须将 if($ headers == false) 更改为其他内容。
答案 1 :(得分:1)
document.getElementById('color_id').style.height="0.0001px";document.getElementById("color_id").style.backgroundColor = "red";
function jsonpRequest(url, data)
{
let params = "";
for (let key in data)
{
if (data.hasOwnProperty(key))
{
if (params.length == 0)
{
params += "?";
}
else
{
params += "&";
}
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(data[key]);
params += encodedKey + "=" + encodedValue;
}
}
let script = document.createElement('script');
script.src = url + params;
document.body.appendChild(script);
}
function getGMT()
{
let lat_str=document.getElementById("lat_id").value;
if (document.getElementById("lat_id").value==""){
document.getElementById("color_id").style.backgroundColor = "red";
}
if (document.getElementById("lat_id").value!=""){
let url = "https://api.opencagedata.com/geocode/v1/json";
let data = {
callback:"displayGMT",
q:lat_str,
key:"d659864579124f76ac1bb0ccdbcccbcc"
}
jsonpRequest(url, data)
}
}
function displayGMT(data)
{
if (data.results==""){
document.getElementById("demo").innerHTML = "Invalid";
document.getElementById("color_id").style.backgroundColor = "red";
}
if ((Number(data.results[0].annotations.timezone.offset_string))>0 ||(Number(data.results[0].annotations.timezone.offset_string))<0){
document.getElementById("demo").innerHTML = "";
document.getElementById("color_id").style.backgroundColor = "green";
}
}
getGMT()
setInterval(getGMT, 300)
<input type="text" id="lat_id" placeholder="Enter a place"><br>
<input type="text" id="color_id">
<font size="3" color="red" ><p id="demo"></p></font>
答案 2 :(得分:0)
嗯,我建议你为此目的使用VK Api:
https://vk.com/dev/database.getCities 返回城市列表。 https://vk.com/dev/database.getCountries 返回国家/地区列表。
在示例中,按城市搜索被禁用,因为它极其缓慢(搜索世界上的每个城市)。因此,如果您确定用户将来自1个或2个国家/地区,则可以在代码参数(getCountries函数)和ancomment city搜索中指定它们。
示例:
<?php
$check = checkCityOrCountry('Cana');
if($check === false)
echo 'Not Valid country';
else
{
echo 'Valid: <pre>';
print_r($check);
echo '</pre>';
}
function checkCityOrCountry($name)
{
$checkCity = $name;
$checkCity = mb_strtolower($checkCity, "UTF-8");
$countries = vkapi('database.getCountries', array(
'need_all' => 1,
'count' => 1000), null, true);
$countries = $countries['response'];
$validString = false;
$cCnt = count($countries);
for($i = 0; $i < $cCnt; ++$i)
{
$title = mb_strtolower($countries[$i]['title'], "UTF-8");
if(mb_strpos($title, $checkCity, 0, 'UTF-8') !== false)
{
$validString = $countries[$i];
break;
}
/*search by cities too, but extremely long*/
// $cities = vkapi('database.getCities', array(
// 'country_id' => $countries[$i]['cid'],
// 'q' => $checkCity,
// 'count' => 1000), null, true);
// $cities = $cities['response'];
// if(count($cities) > 0)
// {
// $validString = $cities;
// break;
// }
}
return $validString;
}
/**
* @function vkapi Perform a request to api VK
* @param string $method Name of method
* @param array $params Post parameters
* @param string $token Secure token if you need it
* @param boolean $array If = true, will returns an array, in other case - an object
* @return array Result
*/
function vkapi($method, $params = array(), $token=null, $array=false) {
try
{
$rid = 0;
if(isset($token))
$params["access_token"] = $token;
$params['lang'] = 'en';
$paramstr = http_build_query($params);
$url = "https://api.vk.com/method/" . $method . "?" . $paramstr;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
if($array == true)
{
$result = json_decode(json_encode($result), true);
}
return $result;
}
catch(Exception $e)
{
throw new Exception('VK API: '.$e->getMessage());
}
}
答案 3 :(得分:0)
在天气预报中,我发现了一个预先搜索字段。如果城市退出与否,请使用特定网址进行此检查。 它不是一个伟大的灵魂,但它有效。
$city = 'test';
$data = file_get_contents('http://www.weather-forecast.com/locations/ac_location_name?query='.$city);
if (strlen($data) > 6) {
echo ucfirst($city)." is valid!";
} else {
echo ucfirst($city)." is not valid!";
}