php youtube json decode

719

I tried to use JSON decode to get the youtube API feed. However, when I paste the JSON result inhttp://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) { 
...
}
359

Answer

Solution:

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

91

Answer

Solution:

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);
}
?>

People are also looking for solutions to the problem: php - Store IPV6 and IPV4 in MySql and also read it

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.