PHP:正确使用html_entities.希望在错误消息中返回所有/任何字符


PHP: Using html_entities correctly. Want all/any characters to be returned in error message

我在错误消息中返回某些字符时遇到问题。设置如下:

无论用户在文本字段中输入什么(如果不正确),都应在错误消息中返回。无论是字母、逗号、& 号...什么。似乎html_entities或special_chars在这里是合适的。

下面的代码块是我认为应该设置这个想法的地方。以下字符返回一条空白错误消息,其中仅附加了字符串(不是有效的 4 个字母的 ICAO 机场代码):

+'"'&

这是有问题的代码。注释掉的 $error_str 是我正在努力工作的。

 else
 {
   //VERIFY ICAO IS IN AIRPORTS.DB
   $airport_query = "SELECT COUNT(*) AS airport_count, LAT, LONG, IATA, Name FROM airports WHERE ICAO = '$icao'";
   $airport_result = $airports_db->queryDB($airport_query);
   foreach($airport_result as $airport_row) {}
     if($airport_row["airport_count"] == 0)
     {
       $error_str = "$icao is not a valid 4-letter ICAO airport code.";
       /* $error_str =  "html_entities($icao) is not a valid 4-letter ICAO airport code."; */     
     }
     $return_array["ICAO"] = $icao;
     $return_array["IATA"] = $airport_row["IATA"];
     $return_array["airport_name"] = $airport_row["Name"];
 }
 $return_array["error"] = $error_str;
 echo json_encode($return_array);  

另请注意底部的echo json_encode。我不确定我是否应该在 $error_str 或 $return_array 上执行html_entities。

任何意见都值得赞赏。

这里有两个主要问题。第一个是 PHP 函数htmlentities名称中没有下划线,第二个是函数调用不能在字符串中。

这将起作用:

$error_str = htmlentities($icao) . ' is not a valid 4-letter ICAO airport code.';

htmlentities接受字符串,因此在$return_array上运行它将不起作用。您可以在将其放入$return_array之前执行htmlentities($error_str)

http://www.php.net/manual/en/function.htmlentities.php