如何在URL中使用带有非ASCII字符的file_get_contents()?

时间:2014-09-26 15:40:21

标签: php html encoding

我当前试图从网站上获取数据,并在我的PHP脚本中使用它。

我想要达到的链接是: http://steamcommunity.com/market/priceoverview/?country=US&currency=3&appid=730&market_hash_name=★%20Bayonet

这是我的代码:

<?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";

1 个答案:

答案 0 :(得分: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);
相关问题