3

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) { 
...
}
Rich
  • 5,603
  • 9
  • 39
  • 61
yuli chika
  • 9,053
  • 20
  • 75
  • 122
  • 2
    `json_decode` is not affected by `$` in the strings. You realize the shown URL gives an `Invalid request URI` error? – mario Mar 20 '11 at 19:16
  • @mario, I want to get the mediadescription. if I ignore `$`, use `echo $result->mediagroup->mediadescription;` it called back `Catchable fatal error: Object of class stdClass could not be converted to string in...` – yuli chika Mar 20 '11 at 19:22

2 Answers2

8

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.)

mario
  • 144,265
  • 20
  • 237
  • 291
0

This work:

<?php
$url = 'http://gdata.youtube.com/feeds/api/videos?q=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) { 
    var_dump($result);
}
?>
Faraona
  • 1,685
  • 2
  • 22
  • 33