file_get_contents(JSON) 不适用于有效的 URL

file_get_contents(JSON) not working for valid URL

我正在尝试从 ULR 获取 JSON,但出现错误:

警告:file_get_contents(http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=StatTrak™ Five-SeveN | Copper Galaxy(全新出厂)):无法打开流:HTTP 请求失败! HTTP/1.0 500 Internal Server Error in F:\Bitnami\htdocs\Dreamweaver\freehtml5streets\updateInventory.php on line 70

这是我正在尝试使用的 URL,如果您访问它,您会看到它有效(您必须复制整个内容):

http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=StatTrak™ 五七N |铜银河(崭新出厂)

我一直在访问类似的 URLs 并获得 JSONs,例如:

http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=AK-47%20%7C%20Redline%20%28Field-Tested%29

这些 URL 基本相同,但第一个没有 HTML 标签。这是我的代码:

        $data = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' . $mydata->market_hash_name);
        $json = json_decode($data);

$mydata->market_hash_name 获取 URL 末尾的部分,但没有 HTML 标签(%20%)等

我怎样才能让它工作?

您似乎需要 urlencode 您的 $mydata->market_hash_name,因为它使用了一些特殊的保留字符。以下应该有效:

//Assuming $mydata->market_hash_name == "StatTrak™ Five-SeveN | Copper Galaxy (Factory New)"

$data = file_get_contents('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=' . urlencode($mydata->market_hash_name));
$json = json_decode($data);

您可能会发现某些域无法使用此方法 (file_get_contents) 检索 url,因为例如远程服务器需要一个有效的用户代理 - 在我看来最好使用 cURL 获取远程页面的内容....