【问题标题】:How do I escape these ampersands in PHP?如何在 PHP 中转义 & 符号?
【发布时间】:2015-05-04 16:14:40
【问题描述】:

我目前正在编写一些使用 Steam 网络 API 的东西,并且我正在尝试通过网络 API 获取 Steam 市场价格,如下所示:

$url = 'http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name='.$itemInfo['market_hash_name'];

$itemInfo['market_hash_name'] 来自我从 API 获得的另一个 JSON。

应该返回如下内容:

http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=SCAR-20 | Contractor (Well-Worn)

确实如此,这很好,因为当我将其放入浏览器时,它会转换为

http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=SCAR-20%20|%20Contractor%20(Well-Worn)

返回我需要的 JSON。

但由于某种原因,当它与get_file_contents 一起使用时,它会像这样翻译与号:

http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=Operation Breakout Weapon Case

如果我把它扔到浏览器窗口中,它什么也不返回。所以我使用htmlspecialcharshtml_entity_decode 并不重要,因为每当我将它放入get_file_contents 时,它只会再次编码与符号。

我该怎么做?

【问题讨论】:

  • 当您看到http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=SCAR-20%20|%20Contractor%20(Well-Worn) 时,您是在浏览器中查看源代码还是输出?
  • 当我运行它时,它返回成功:var_dump(file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=SCAR-20 | Contractor (Well-Worn)'));

标签: php json escaping steam steam-web-api


【解决方案1】:

因此,我使用 htmlspecialchars 还是 html_entity_decode 并不重要,因为每当我将它放入 get_file_contents 时,它只会再次对 & 符号进行编码。

这些都不用于 URI 编码。这是urlencode 的工作。

所以:

$url = 'http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name='.urlencode($itemInfo['market_hash_name']);

【讨论】:

  • 我已经尝试过 urlencode,但 ofc 只需要在 itemInfo 上...我的错,谢谢 :)
猜你喜欢
  • 2012-04-23
  • 2014-11-10
  • 2013-09-15
  • 2016-09-10
  • 2013-11-22
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-01-18
相关资源
最近更新 更多