在网站上工作,我正在访问 Steam API 以返回用户的 CSGO 元素 list
这是我点击的网址
$response = $this->guzzle->request('GET', "http://steamcommunity.com/profiles/{$communityId}/inventory/json/730/2");
所以在 dev/locally 中,这一切都适用于以下内容
foreach (json_decode($response->getBody()->getContents(), true)['rgDescriptions'] as $item) {
$inventory[$item['name']] = $item;
}
return $inventory;
但是当我更新我的网站时,它提示我的 foreach 循环的参数无效 - 在 var 转储之后 - ($response->getBody()->getContents()) - 仅在实时网站上 返回的 json 数据包含奇怪的东西 - 我一般是 json 的新手,但它包含如下内容
"""
00006000\r\n
{"success":true,"rgInventory":{"8161072596":{"id":"8161072596","classid":"1560432042","instanceid":"480085569","amount":"1","pos":1},"8159918836":
和这样的结束 block
{"internal_name":"normal","name":"Normal","category":"Quality","category_name":"Category"},{"internal_name":"Rarity_Ancient","name":"Extraordinary","category":"Rarity","color":"eb4b4b","category_name":"Quality"}]}},"more":false,"more_start":false}\r\n
00000000\r\n
\r\n
"""
所以这当然是我的 foreach 中断的原因,因为我的响应的 json_decode 将返回 null 而不是 assoc 数组? (查看底部的完整功能!)
虽然我不确定,但我很确定这些是换行符?它相当烦人我不确定我是否遗漏了我这边的某些东西或者它来自 Steam 的响应,尽管我看不到当我在开发上工作正常时它是怎样的?
我在研究中也遇到了 magic_quotes,但我读到它们在 php 5.4 中被贬值了?我运行的是 5.6,所以我只能认为服务器端一定还有其他我遗漏的东西?
下面是我的辅助函数,供引用
public function getCSGOInventory($communityId)
{
$response = $this->guzzle->request('GET', "http://steamcommunity.com/profiles/{$communityId}/inventory/json/730/2");
$inventory = [];
foreach (json_decode($response->getBody()->getContents(), true)['rgDescriptions'] as $item) {
$inventory[$item['name']] = $item;
}
return $inventory;
}
最佳答案
我之前遇到过同样的问题。问题是 json 代码中的随机数,如 00000000 和 00006000。这看起来是 Guzzle 中的一个错误。我能够通过安装 php-curl 包来修复它。尝试像这样执行 apt-get 来解决问题(如果您使用的是像 Ubuntu 这样的操作系统):
sudo apt-get install php-curl
您可以在这里找到更多相关信息: https://github.com/guzzle/guzzle/issues/1385
关于php - 处理来自第 3 方的无效 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809963/