Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php youtube json decode

Tags:

json

php

I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result in http://www.jsonlint.com/ I noticed something like

"media$group": {
  "media$category": [

Unfortunately some symbols are rejected by php. Here is my code, I tried to remove this $ symbol, but maybe not success. How do I solve this?

$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) { 
...
}
like image 292
yuli chika Avatar asked Nov 23 '25 12:11

yuli chika


1 Answers

Your problem is the usage of PHP identifiers to access the contents. The simplest solution here would be to get an array instead of an object:

$data = json_decode ( $json , $assoc = true );

This allows access to fields with:

echo $result['media$group']['media$description'];

If you want to keep the object syntax, that's possible with this kludge:

echo $result->{'media$group'}->{'media$category'};

(But arrays are safer here. You don't get a fatal error should the format change and properties be absent.)

like image 140
mario Avatar answered Nov 26 '25 04:11

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!