Home > OS >  How to separate text file data into an an array in PHP
How to separate text file data into an an array in PHP

Time:11-18

So I have a text file which contains questions and answers to a trivia game, each anwser is seperated from its question with a tab ("\t") and each question/anwser combination is on its own line. Like this:

In which movie does Michael J. Fox play a time-travelling teenager?    Back to the Future
In 'Old School', what song does Frank try and sing at Blue's funeral.  Dust In The Wind
What hiphop heroes joined forces with Aerosmith for a new version of Walk This Way?    Run DMC
What singer's February 6 birthday is a national holiday in Jamaica?    Bob Marley
What year did Steven Page leave BNL?   2009
What is a group of turtles known as?   A pod

I am trying to create an array where I can separate questions and answers, but it keeps giving me an array with a size of 2 and the output is a group of all the questions or a group of all the answers and i cant seem to separate them any further. Here is what I have so far:

$fileHandler = fopen('triviaQuestions.txt', 'r');

if ($fileHandler) {
    while (($line = fgets($fileHandler)) != false) {
        $line = explode("\t", $line);

        echo $line[0];
    }
    fclose($fileHandler);
}

This is the output I get from that:

In which movie does Michael J. Fox play a time-travelling teenager?In 'Old School', what song does Frank try and sing at Blue's funeral.What hiphop heroes joined forces with Aerosmith for a new version of Walk This Way?What singer's February 6 birthday is a national holiday in Jamaica?What year did Steven Page leave BNL?What is a group of turtles known as?

As you can see it just groups all the questions as $line[0] rather than separate them from each other. It does the same thing to the answers when I try $line[1].

CodePudding user response:

<?php

$fileHandler = fopen('triviaQuestions.txt', 'r');

if ($fileHandler) {

    $ques = [];
    $ans = [];

    while (($line = fgets($fileHandler)) !== false) {

        $line = explode("   ", $line);

        // Not each anwser is seperated from its question with a tab.
        // For example:
        // In 'Old School', what song does Frank try and sing at Blue's funeral.  Dust In The Wind
        if (!isset($line[1])) {
            $line = explode("  ", $line[0]);
        }

        $ques[] = $line[0];
        $ans[] = $line[1];

    }

    $counter = 0;
    $str = "";

    foreach ($ques as $que) {

        $answer = $ans[$counter];
        $counter  = 1;

        $str .= "Q: " . $que;
        $str .= "<br />";
        $str .= "A: " . $answer;
        $str .= "<br />";
        $str .= "<hr />";

    }

    echo $str;
    fclose($fileHandler);

}
  • Related