使用$ GET从文本文件中读取特定行,然后回显它

时间:2015-07-17 10:04:17

标签: php get echo

我有一个已经由用户创建并附加的文本文件,我使用这种格式来附加它。每次输入后换行并用分号分隔:

电影标题1;电影评分1; Plot1;

电影标题2;电影评分2; Plot2;

电影标题3;电影评分3; Plot3;

等。等

我已经设法解决了上述问题,现在我想从文本文件中读取一个特定的行然后回显它。这个特定的行可以通过$ GET参数找到并基于Movie Title。

例如,我点击链接,在这种情况下是电影中的标题,然后我通过$ GET获取标题名称:movies.php更改为movies.php?title = MovieTitle。然后我得到这个当前的电影标题名称并阅读这个特定的行并回应它。这是我的代码:

//Writes input from user to movies.txt
<?php
    if (isset($_POST["submit"])) {
        $title = $_POST['movieTitle'];
        $rating = $_POST['movieRatings'];
        $plot = $_POST['plot'];


    $handle = fopen('movies.txt', 'a');
    $names_array = array("$title","$rating","$plot");
    $string = implode(';', $names_array);
    fwrite($handle, $string."\n");          
    fclose($handle);
    }   
    ?>

//Reads line from movies.txt and adds it to a li, with movie title becoming a link
<?php
    $filename = 'movies.txt';

    $handle = fopen($filename, 'r');

    $datain = fread($handle, filesize($filename)); 

    $lines = explode ("\n",trim($datain));
    foreach($lines as $line)
    {
        list($title,$rating,$plot) = explode(";",$line,3);
        echo '<li><a href="movies.php?title='.$title.'">'.$title.'</a><span>'.$rating.'</span></li>';
    }
    ?>//So far so good

//And now I want to read title name, and based on the
//title name find a specific line with rating and plot 
//which belongs to current clicked movie title...
<?php
if (isset($_GET["title"])) {
    $readin = file('movies.txt');

    foreach ($readin as $fname) 
    $names_array = explode(';', $fname);
    {
            echo '<h1>'.$names_array[0]./*MovietitleName*/'</h1>''<h2>'.$rating.'</h2>'.$plot;//So I want to echo the specific "movieTitle movie, movieRating and moviePlot". What I've done so far is wrong, I need help here! 
    }
    }
?>

所以我想用电影名称和电影评级来回应它。我希望你能理解我的问题,提前谢谢!

2 个答案:

答案 0 :(得分:1)

首先,你的语法有错误。其次,这是您的解决方案的数据库不会扩展。然而,为了让它工作做类似......

if (isset($_GET["title"])) {
  $readin = file('movies.txt');

  foreach ($readin as $fname) 
  {
     $names_array = explode(';', $fname);//this has to go here
     if($_GET['title']===$names_array[0]){//only echo if the title mathces
        echo '<h1>'.$names_array[0]./*MovietitleName*/'</h1>''<h2>'.$names_array[1].'</h2>'.$names_array[2];
     }
  }
}

答案 1 :(得分:1)

试试此代码

if (isset($_GET["title"])) {
  $readin = file('movies.txt');

  foreach ($readin as $fname) 
  {
     $names_array = explode(';', $fname);//this has to go here
     if($_GET['title']==$names_array[0]){
        echo '<h1>'.$names_array[0].'</h1><h2>'.$names_array[1].'</h2>'.$names_array[2];
     }
  }
}