将数据发布到json url时出现问题

时间:2013-05-28 00:31:42

标签: php json post youtube-api

嘿,我确定这是一个简单的解决办法,但它让我疯狂。

我正在使用youtube api,我正试图将用户生成的搜索字词发布到网址中,如下所示:

<form action="pagination.php" method="post">
<input style="width:50%" type="text" name="search_term">
<input type="submit" value="Submit">
</form>

<?

$search_term = $_POST['search_term'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://gdata.youtube.com/feeds  
/api/videos?q='.$search_term.'&safeSearch=none&orderby=viewCount&v=2&alt=json&start- 
index=75&max-results=50');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch); 

$data = json_decode($output,true);

$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);



echo "<ul style='float:right'>";
foreach($video as $video) {
echo '<img src="'.$video['media$group']['media$thumbnail'][0]['url'].'"><br><br>';
$title = $video['title']['$t'];
$video_id = $video['media$group']['yt$videoid']['$t'];
echo '<a href="search_4.php?video_get_id='.$video_id.'">'.$title.'</a>';
echo '<br>';

当我运行此代码时没有任何反应,但如果我手动为$ search_term分配一个值,如下所示:

$search_term = 'baseball';

一切都很完美。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我发现了一些语法错误。 以下代码适用于我。 注意:更改文件名,以便您可以测试此文件并更新您自己的文件中的代码。 也许是故意的,但是在开始时它总是会以“无条件”进行检索,因为代码已经执行了。

ENTER terms and press Submit button
<form action="ytcurltest1.php" method="post">
<input style="width:50%" type="text" name="search_term">
<input type="submit" value="Submit">
</form>

<?PHP
$search_term = $_POST['search_term'];
$startIndex = 1;
$maxResults = 25;
$ch = curl_init();
$url =  'http://gdata.youtube.com/feeds/api/videos?q='
     . $search_term
     . '&safeSearch=none&orderby=viewCount&v=2&alt=json'
     . '&start-index=' . $startIndex
     . '&max-results=' . $maxResults;
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch); 

$data = json_decode($output,true);
if ( count($data) == 0 )
  {
    echo 'NO RESULTS FOUND. ENTER other terms';
    RETURN;
  }
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);

echo "<ul style='float:right'>";
foreach ($video as $video)
    {
     echo '<img src="'.$video['media$group']['media$thumbnail'][0]['url']
          .'"><br><br>';
     $title = $video['title']['$t'];
     $video_id = $video['media$group']['yt$videoid']['$t'];
     echo '<a href="search_4.php?video_get_id='.$video_id.'">'.$title.'</a>';
     echo '<br>';
   }
?>