1

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.

4
  • 4
    Somewhere you are referencing $collectionViewUrl without the $ sign Commented Mar 12, 2015 at 15:20
  • @robbmj is correct. Post the code where you reference collectionViewUrl. Commented Mar 12, 2015 at 15:22
  • This is what I was using echo $json_result[collectionViewUrl]; Commented Mar 12, 2015 at 15:26
  • The problem was that collectionViewUrl was not quoted $json_result["collectionViewUrl"]; also you were not looking in the correct array as noted in @Khaled Bentoumi answer. Commented Mar 12, 2015 at 15:29

1 Answer 1

2

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 !

Sign up to request clarification or add additional context in comments.

2 Comments

This works, many thanks for your assistance. marked as answer
@omega1 you're welcome happy to help, could you check it as answered so that it could help futur user ? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.