没有从$ youtube_array返回数组而是给对象(stdClass)#1

时间:2012-05-08 16:26:40

标签: php arrays api

我正在尝试请求一个youtube数组,但var dump显示一个以object开头的转储(stdClass)#1

<?php
$num = Rand(1,5);
switch ($num) {
case 1: header('Foo Fighters The Pretender'); $music= 'Foo Fighters The Pretender';
case 2: header('Arctic Monkeys Flourescent Adolescent'); $music= 'Arctic Monkeys Flourescent Adolescent';
case 3: header('The Strokes Under Cover of Darkness'); $music= 'under cover of darkness';
case 4: header('The White Stripes Seven Nation Army'); $music= 'the white stripes seven nation army';
case 5: header('Franz Ferdinand Michael'); $music= 'franz ferdinand michael';
}
$youtube_array = json_decode(file_get_contents("https://gdata.youtube.com/feeds/api/videos?alt=json&q=" . urlencode($music) , TRUE ));
var_dump($youtube_array);
echo "<h1>Your Song Is:</h1>";
echo $music;
echo "</p>";
echo "YouTube found this video about your Rock:";
echo "</p>";
$link = $youtube_array['feed']['entry'][0]['id']['$t'];
$link2 = substr($link, 42);
echo "<iframe width='960' height='720' src='http://www.youtube.com/embed/" . $link2 . "' frameborder='0' allowfullscreen></iframe>";
?>

2 个答案:

答案 0 :(得分:1)

你在这一行中错放了右括号:

$youtube_array = json_decode(file_get_contents("-" . urlencode($music) , TRUE ));

应该是

$youtube_array = json_decode(file_get_contents("-" . urlencode($music)), TRUE );

答案 1 :(得分:0)

json_decode有第二个参数([,bool $ assoc = false ....)。如果保留默认值,它将返回一个对象。如果是真的,它会设置一个关联数组。

您的代码中包含'file_get_contents($filename [, bool $use_include_path...'

的'true'