PHP中使用echo输出HTML失效问题求助
问题:PHP输出包含HTML的文本时仅显示链接文本,其余内容缺失
我在PHP里尝试输出带HTML跳转链接的提示信息,写法是用echo输出转义后的HTML标签(比如<a href="url">text</a>),但从localhost访问文件时,页面只显示“Click here”这几个字,其他提示文本完全看不到。我试过拆分PHP标签、在文件顶部添加DOCTYPE声明、改用print函数等方法,结果都没解决问题。
我的完整PHP代码如下:
<?php require_once 'include/DB_Functions.php'; $db = new DB_Functions(); $token = $_GET["key"]; $redirect = 'Redirecting to login page in 5 seconds. If it does not work, <a href="localhost:51631/login.aspx">click here</a> to do it manually.'; if(isset($_GET["key"]) && $token !== "") { $unique_id = $db->getUniqueIdFromToken($token); if(is_null($unique_id)) echo 'Key not found.' . $redirect; else { $verify = $db->verifyAccount($unique_id); if($verify) echo 'Account is successfully verified. ' . $redirect; else echo 'Account could not be verified. ' . $redirect; } } else echo 'Key is missing.' . $redirect; ?>
排查与解决过程
后来在Progman的建议下,我检查了请求响应头,得到的结果如下:
array (size=2) 0 => string 'X-Powered-By: PHP/5.5.12' (length=24) 1 => string 'Content-type:application/json;charset=utf-8' (length=43) string 'BREAK' (length=5) array (size=1) 'X-Powered-By' => string 'PHP/5.5.12' (length=10)
这才找到问题根源:响应头的Content-Type被设置成了application/json,浏览器会按照JSON规则解析内容,导致除链接文本外的其他内容都被“隐藏”了。
进一步追踪发现,这个JSON类型的Content-Type头是通过require_once引入的DB_Functions.php文件自动添加的。我把该文件里设置Content-Type的代码移除后,页面就正常显示所有文本和HTML链接了!
内容的提问来源于stack exchange,提问作者Furkan Yurdakul
相关产品推荐
相关产品推荐

