user3481202 user3481202 - 2 months ago 6
PHP Question

Read questions from a plain text file

I want to read questions from a text document in PHP and sort them in an

array()
.

The resulting array should look like this:

print_r($questionnaire);

array(
'question 1' => array('yes','no'),
'question 2' => array('yes','no'),
'question 3' => array('yes','no'),
...etc
)


My text document is:

question 1?
yes
no
question 2?
yes
no
question 3?
yes
no


I am trying this:

$txt_doc = $_FILES['txt_doc']['tmp_name'];

$questions_and_answers = array();

$handle = fopen($txt_doc, 'r') or die($txt_doc . ' : CAnt read file');


$i = 0;
while ( ! feof($handle) )
{
$line = trim(fgets($handle));

if(strstr($line, '?'))//its a question
{
$questions_and_answers[$i] = $line;$i++;
}
if(!strstr($line, '?'))
{
$questions_and_answers[$i][] = $line;
}

}

Answer

In order to produce the output you want, you'll need to use the question as an array key in $questions_and_answers. If you do this, $i becomes unnecessary. You can do the same check for question mark that you're doing, and when you get to a question, create a new key. Then use that key for subsequent lines (answers) until you get to the next question.

while (!feof($handle)) {
    $line = trim(fgets($handle));
    if (strstr($line, '?')) {                          // it's a question
        $question = $line;
    } else {                                           // it's an answer
        $questions_and_answers[$question][] = $line;
    }
}
Comments