Rune Rune - 25 days ago 6
JSON Question

How do I escape these ampersands in PHP?

I'm currently writing something that uses the Steam web API and I'm trying to get the Steam market price via the web API like so:

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


The
$itemInfo['market_hash_name']
is something from another JSON I got from the API.

That should return something like this:

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


and it does, which is fine, because when I throw that into the browser, it translate into

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


which returns the JSON I need.

But for some reason when it's used with
get_file_contents
, it translates the ampersands like so:

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


Which returns nothing if I throw it into a browser window. So it doesn't really matter if I use
htmlspecialchars
or
html_entity_decode
, because whenever I put it into
get_file_contents
it just encodes the ampersands once again.

How am I to do this?

Answer

So it doesnt really matter if i use htmlspecialchars or html_entity_decode, cuz whenever i put it into get_file_contents it just encodes the ampersands once again.

Neither of those is for URI-encoding. That's the job of urlencode.

So:

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