Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Special Characters within URL Variable

Tags:

php

Currently I am trying to fiddle around with the Deezer API and running into a slight issue, I am trying to gather content from this artist.

XYLØ - Nothing Left To Say

https://api.deezer.com/search/track?q=XYLØ - Nothing Left To Say

The page above displays the content in a JSON format, however when I use the following code.

$id = 'XYLØ - Nothing Left To Say';
$h = str_replace(' ', '+', $id);
$json_string = 'https://api.deezer.com/search/track?q='.$h;
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);

I get an empty pallet on my image request.

$obj['data'][0]['album']['cover_medium']

Any ideas on how I can get this to work properly?

like image 222
Lonely Stoner Avatar asked Nov 06 '22 20:11

Lonely Stoner


1 Answers

Use PHP's built in function for query args,

 //changed $h to $id (see below)
$json_string = 'https://api.deezer.com/search/track?q='.urlencode($id);

http://php.net/manual/en/function.urlencode.php

This function is convenient when encoding a string to be used in a query part of a URL, as a convenient way to pass variables to the next page.

You can also do away with this stuff (AKA remove it):

  $h = str_replace(' ', '+', $id);

As urlencode does that to!!!.

As a Bonus

You can use

http://php.net/manual/en/function.http-build-query.php

http_build_query — Generates a URL-encoded query string from the associative (or indexed) array provided.

To build the whole query string from an array, which I figure may be useful to someone reading this...

like image 149
ArtisticPhoenix Avatar answered Dec 05 '22 21:12

ArtisticPhoenix