omega1
omega1

Reputation: 1052

Putting json content into PHP variable

I need to manipulate some data which is being given to me in json format, from which I need to extract some data and put into a variable in PHP.

Having tried my best, I seem to end up with errors such as :

Use of undefined constant collectionViewUrl - assumed 'collectionViewUrl'

At the moment the only real code I have is this:

$string = file_get_contents("https://itunes.apple.com/search?term=rihanna+diamonds&country=gb&media=music&entity=musicTrack&attribute=musicTrackTerm&limit=1");
$json_result = json_decode($string, true);

I do not need an array of any kind, I just need to put the value of collectionViewUrl into a variable.

Upvotes: 1

Views: 1123

Answers (1)

BentoumiTech
BentoumiTech

Reputation: 1683

Here how to get the collectionViewUrl string into a variable

$string = file_get_contents("https://itunes.apple.com/search?term=rihanna+diamonds&country=gb&media=music&entity=musicTrack&attribute=musicTrackTerm&limit=1");
$json_result = json_decode($string, true);
$collectionViewUrl = $json_result['results'][0]['collectionViewUrl'];

Here is a codepad where you can try the code http://codepad.org/6Zogs3si

Explanation :

When the 2nd parameter of json_decode is set to true the function return an associative array who's really close to the structure of the JSON.

From there all what you got to do is put back the JSON path into an associative php array to access the wanted value !

Upvotes: 2

Related Questions