April 23, 2012
how to parse json in php and javascript
Question by Jetoox
http://gdata.youtube.com/feeds/users/LadyGagaVEVO/uploads?alt=json&max-results=10&format=5
I would like to extract the video thumbnail and video link using PHP and JavaScript from the url above but I’m not sure how to do it, here is my attempt so far:
$json = 'http://gdata.youtube.com/feeds/users/LadyGagaVEVO/uploads?alt=json&max-results=10&format=5';
$data = json_decode($json);
print_r($data);
Answer by Gäng Tian
in PHP
$tmp = file_get_contents('http://gdata.youtube.com/feeds/users/LadyGagaVEVO/uploads?alt=json&max-results=10&format=5/');
$data = json_decode($tmp,true);
in javascript with jquery
$.get("http://gdata.youtube.com/feeds/users/LadyGagaVEVO/uploads?alt=json&max-results=10&format=5/", function(response) {
var data = $.parseJSON(response);
});
about the illegal character, depends on what counts as illegal in your case, just do some string validation as you traverse through the object for the thumbnail and video link you looking for.
Answer by Starx
Using, PHP as you are doing, use json_decode(). but use it one extra paramter
$data = json_decode($string, true); // the true in the last will change into associative array
For JavaScript, as Kolink said, use JSON.parse()