【问题标题】:How to use file_get_contents() with non-ASCII characters in URL?如何在 URL 中使用带有非 ASCII 字符的 file_get_contents()?
【发布时间】:2014-09-26 15:40:21
【问题描述】:

我目前正在尝试从网站获取数据,并在我的 PHP 脚本中使用它。

我要访问的链接是: http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★%20刺刀

这是我的代码:

<?php

$skin = $_GET['market_hash_name'];
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin."";
$FN = file_get_contents($link);

echo $FN;
?>

这就是我使用链接的方式:

http://myhost.com/getPrice.php?market_hash_name=★ Bayonet

这是我得到的错误:

警告:file_get_contents(http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=â~... Bayonet):打开流失败:HTTP 请求失败!第 5 行 F:\xampp\htdocs\getPrice.php 中的 HTTP/1.0 500 内部服务器错误

编辑:

好的,所以我找到了解决问题的方法,但是现在出现了一个新错误:

警告:file_get_contents(http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=%E2%98%85+Bayonet+%7C+Stained (Factory New)):打开流失败:HTTP 请求失败!第 7 行 F:\xampp\htdocs\getPrice.php 中的 HTTP/1.0 500 内部服务器错误

这就是我现在使用链接的方式:

getPrice.php?market_hash_name=★ 刺刀 |染色

这是我的代码:

function getPrice($string) {
$skin = urlencode($_GET['market_hash_name']);
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin." ".$string;
$content = file_get_contents($link);
$data = json_decode($content, true);
return $data['lowest_price'];
}
$FN = getPrice("(Factory New)");
$MW = getPrice("(Minimal Wear)");
$FT = getPrice("(Field-Tested)");
$WW = getPrice("(Well-Worn)");
$BS = getPrice("(Battle-Scarred)");


echo "Factory New: $FN; Minimal Wear: $MW; Field-Tested: $FT; Well-Worn: $WW; Battle-Scared: $BS";

【问题讨论】:

  • http://steamcommunity.com/market/priceoverview/?country=US&amp;currency=3&amp;appid=730&amp;market_hash_name=%E2%98%85%20Bayonet
  • 尝试设置 unicode 字符而不是复制/粘贴这个天气字符:★
  • 根据您的编辑,您需要使用 Curl。
  • 想举个例子吗?
  • 在 Stack stackoverflow.com/q/14953867 上查看此问答 - 您可以通过谷歌搜索“curl website php”来进一步研究。您会发现很多结果,其中一些可能会引导您返回 Stack 上的其他问答。

标签: php html encoding


【解决方案1】:

在其他字符中,非 ASCII 字符必须在查询字符串中为 URL-encoded (aka percent-encoded)

$skin = url_encode($_GET['market_hash_name']);
$link = "http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=".$skin."";
$FN = file_get_contents($link);

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 2013-06-19
    • 2023-03-25
    • 2011-10-07
    • 2020-12-21
    • 1970-01-01
    • 2011-06-08
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多