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");
print(json_encode(array('venues'=>$data)));

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 &

Questions:

  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
douxu2467 我会发一个答案,完全解释我在说什么。
5 年多之前 回复
doupeng8419
doupeng8419 所以我不应该在插入过程中使用htmlspecialchars,但只有当我在网页上显示数据时?
5 年多之前 回复
douze1332
douze1332 你为什么要进入数据库的html编码?您应该将要放入HMTL文档的文本编码,而不是原始数据。改变你这样做的方式吗?如果是这样,我会将其作为答案发布。
5 年多之前 回复

1个回答

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:

<?php
$db = //get database connection
$data = $db->read//....
?>
<div>
<?=htmlspecialchars($data)?>
</div>
dsmupo6631
dsmupo6631 这正是我的观点。 您可能最初转义了HTML字符,因此当您从数据库中取出数据时,您不必执行此操作,因为它们都是HTML页面。 既然你现在在其他地方需要它,你就会看到这样做的问题。
5 年多之前 回复
doushi4633
doushi4633 好的,但这个数据不适用于网页消费,它适用于Android应用,但我看到你在说什么。 我将插入数据raw
5 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐