PHP Web Service将HTML字符作为实体返回

I have a PHP web service which returns data in JSON format. I have a custom backend to maintain the data. When I save a record via the backend I use htmlspecialchars() on string fields.

An example web service call would run this code:

$dbh = getConnection('read');

$sql = "SELECT Name, Location FROM Venues WHERE id = :venueID";
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':venueID' => $venue));
$data = $sth->fetchAll(PDO::FETCH_ASSOC);

header("Content-type: application/json");

So lets assume that for the provided venue ID the name has a & in it. The web service is called by an Android application so in the application it is displayed as a & and not &


  1. Do I tweak the custom backend to not use htmlspecialchars? I am the only admin so the data going in is safe
  2. Is there a way to run htmlspecialchars_decode on the resultset without looping through the results before I print the JSON?
douxu2467 我会发一个答案,完全解释我在说什么。
5 年多之前 回复
doupeng8419 所以我不应该在插入过程中使用htmlspecialchars,但只有当我在网页上显示数据时?
5 年多之前 回复
douze1332 你为什么要进入数据库的html编码?您应该将要放入HMTL文档的文本编码,而不是原始数据。改变你这样做的方式吗?如果是这样,我会将其作为答案发布。
5 年多之前 回复


The real answer here is that you should not be html encoding data that is going into your database. You want the data in your database to be exactly what the user entered.

An engineer is not expecting data in the database to be escaped in any way. As you can see, doing this forces you to remember to unencode the data whenever you take it out of the database. The problem in your case, is that htmlspecialchars is never meant to be reversed as the browser takes care of that for you in its rendering of the HTML.

You would normally use HMTL escaping in PHP templates like so:

$db = //get database connection
$data = $db->read//....
dsmupo6631 这正是我的观点。 您可能最初转义了HTML字符,因此当您从数据库中取出数据时,您不必执行此操作,因为它们都是HTML页面。 既然你现在在其他地方需要它,你就会看到这样做的问题。
5 年多之前 回复
doushi4633 好的,但这个数据不适用于网页消费,它适用于Android应用,但我看到你在说什么。 我将插入数据raw
5 年多之前 回复
Csdn user default icon