我正在尝试通过 php 通过读取 CSV 文件来制作促销代码验证器。这是我的验证器的代码,而“test.csv”是我的 csv 文件:
<?php
// if data are received via POST, with index of 'test'
if (isset($_POST['test'])) {
$file = fopen('test.csv', 'r');
$coupon = array($_POST['test']);
$coupondef = $_POST['test']; // get data
$coupon = array_map('preg_quote', $coupon);
$regex = '/'.implode('|', $coupon).'/i';
while (($line = fgetcsv($file)) !== FALSE) {
list($promocode, $amount) = $line;
if(preg_match($regex, $promocode)) {
echo "Coupon: '<i>".$coupondef."</i> is valid, with ".$amount."% of discount";
$promocodevalid = 1;
break;
} else {
echo "Coupon: '<i>".$coupondef."</i> is invalid.";
$promocodevalid = 0;}
}
}
?>
这是我的 HTML 代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ro">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax POST</title>
<script type="text/javascript"><!--
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxrequest(php_file, tagID) {
var request = get_XmlHttp();
var the_data = 'test='+document.getElementById('txt2').value;
request.open("POST", php_file, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data);
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<h3 style="cursor:pointer;" onclick="ajaxrequest('couponcheck.php', 'context')"><u>Click</u></h3>
<input type="text" id="txt2" value=""></div>
<div id="context">Here will be displayed the response from the php script.</div>
</body>
</html>
CSV 文件每行有 2 列 - 第一个是优惠券代码,第二个是折扣金额。如果此处理器成功搜索输入的代码,它将返回折扣金额和一行字回原始文件(带有 javascript ajax 发送方/接收方的 html)。如果找不到代码,它将向页面发送无效消息。
问题是,由于我的 csv 文件中有超过 100 行,100 行无效消息将发布到我的接收者页面。(或在成功找到代码之前的行数)我想如何让它在发回响应之前搜索 csv?