使用PHP从用户输入中搜索文本文件


Search Text Files with PHP from User Input

正在寻找通过邮政编码列表进行搜索的解决方案。我有一个文本文件,里面有一堆我们提供服务的邮政编码。希望在网站上有一个表格,要求用户输入他们的邮政编码,看看我们是否为该地区提供服务。如果是,则显示一条消息,说明我们是这样做的,如果不是,则说明我们不是这样做的。本以为PHP是解决我问题的最佳方案,但说到这一点,我完全不懂。

我已经设置好了表单,只是不知道如何搜索文本文件并在另一个div中显示答案?

<form action="zipcode.php" method="post">
<input type="text" name="search" />
<input type="submit" />
</form>

更新:最好是AJAX解决方案!

AJAX方法(已测试)


PHP处理程序

(find_in_file_ax.php)

<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("'n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
    echo "ZIP code found";
}else{
    echo "ZIP code does not exist";
}
?>

HTML表单

<!DOCTYPE html>
<html>
<head>
<style>
.update {
font-family:Georgia;
color:#0000FF;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $(".search_button").click(function() {
        // getting the value that user typed
        var searchString = $("#search_box").val();
        // forming the queryString
        var data = 'search='+ searchString;
        // if searchString is not empty
        if(searchString) {
            // ajax call
            $.ajax({
                type: "POST",
                url: "find_in_file_ajax.php",
                data: data,
                beforeSend: function(html) { // this happens before actual call
                    $("#results").html(''); 
                    $("#searchresults").show();
                    $(".word").html(searchString);
               },
               success: function(html){ // this happens after we get results
                    $("#results").show();
                    $("#results").append(html);
              }
            });    
        }
        return false;
    });
});
</script>
</head>
<body>
<div id="container">
<div>
<form method="post" action="">
    <input type="text" name="search" id="search_box" class='search_box'/>
    <input type="submit" value="Search" class="search_button" /><br />
</form>
</div>      
<div>
<div id="searchresults">Search results: <span id="results" class="update"></span>
</div>
</div>
</div>
</body>
</html>

原始答案

已测试

首先需要通过file_get_contents访问文件,然后分解每个条目并提取有问题的邮政编码搜索。

假设zipcodes.txt文件的格式如下:

43505
43517
43518
43526
43543

注意:如果查询43505,将找到它。与4350或3505不同,它不会被找到,所以它是一个唯一的查询。

考虑以下内容:

<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("'n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
    echo "ZIP code found.";
}else{
    echo "ZIP code does not exist";
}
?>

看到您的编辑。。。下面是PHP。

我会做一些类似的事情

$lines = file("/path/to/file.txt", FILE_IGNORE_NEW_LINES); //reads all values into array
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
    echo "found zip code";
}else{
    echo "zip code does not exist";
}

只要没有大量的邮政编码。。。这应该没问题。此外,您的文件格式是什么?这可能不起作用。