1

我编写了一个脚本来对一些点进行地理编码,这些点的结构基本上是这样的:

//get an unupdated record
$arr_record;
while(count($arr_record) > 0)
{
//strings are derived from $arr_record
geocode($string1);
geocode($string2);
geocode($string3);
array_pop($arr_record);
}

function geocode($string) {
   //if successful
      update($coords)
}

function update($coords) {
   //update the database
   header('Location:http://localhost/thisfile.php')
}

问题在于,即使地理编码成功并且数据库已更新,并且重新发送了标头,脚本仍会返回到 while 循环,而无需重新加载页面并重新开始新记录。

这是 PHP 的正常行为吗?我如何避免它表现得像这样?

4

3 回答 3

5

在 header() 之后使用 die(); 终止脚本和输出。

于 2009-07-11T11:47:33.807 回答
3

我如何避免它表现得像这样?

将 exit() 放在 header() 之后。

于 2009-07-11T11:47:56.677 回答
0

另一种有效的方法是不要直接在循环中发送标头。这是不正确的(我在 php.net 手册中找不到,但我记得之前在 phpusenet 中讨论过)。它在不同的 php 版本中可能会出乎意料。& 不同的 Apache 版本。安装。php 作为 cgi 也会产生问题。

您可以将其分配为以字符串形式返回,然后您可以稍后发送标头...

function update($coords) {
       //update the database

       if(statement to understand update is ok){ 
       return 'Location:http://localhost/thisfile.php';
       } else {  
           return false;   
       }
    }

   if($updateresult=update($cords)!=false){ header($updateresult); }

但如果我是你……我会尝试使用 ob_start() ob_get_contents() ob_end() 因为这些是控制将发送到浏览器的内容的绝佳方式。正常的 mimetypes 或标题...随便。这是同时处理标题和 html 输出的更好方法。

ob_start();  /* output will be captured now */
  echo time();  /* echo test */
  ?>
    print something more...
  <?php  /* tag test */

 /* do some stuff here that makes output. */

$content=ob_get_contents(); 
ob_end_clean();
 /* now everything as output with echo, print or phptags. 
    are now stored into $content variable 
    then you can echo it to browser later 
 */

echo "This text will be printed before the previous code";
echo $content;
于 2009-07-11T12:51:37.683 回答