Kathlyn
Kathlyn

Reputation: 233

Php flatfile database with tabs

I have written this HTML list you can see in the snippet:

<head>
  <style>
    div input + div > div {
      display: none;
    }
    div input:checked + div > div {
      display: block;
    }
  </style>
</head>


<body>

  <div>
    <label for='boys'>Boys</label>
    <input type='checkbox' id='boys' />
    <div>
      <div>Mathew</div>
      <div>Mark</div>
      <div>Kirk</div>
      <div>John</div>
    </div>
  </div>

  <div>
    <label for='girls'>Girls</label>
    <input type='checkbox' id='girls' />
    <div>
      <div>Mary</div>
      <div>Sue</div>
      <div>Jessica</div>
      <div>Alice</div>
    </div>
  </div>

</body>

I want to create a php page with the following flatfile txt database to obtain the same result:

Boys
    Mathew
    Mark    
    Kirk
    John

Girls
    Mary
    Sue
    Jessica
    Alice

My question is: HOW CAN I CREATE A PHP TO READ THE FLATFILE DATABASE ABOVE?

I know I don't supply a background php code but this is my first step of a project and I don't know how to start. Sorry, thanks in advance.

Upvotes: 1

Views: 72

Answers (1)

hherger
hherger

Reputation: 1680

Here's an idea on how you could proceed:

<?php

$filename = 'path/filename.ext';

// Read the file into an array of lines
$lines = file($filename, FILE_IGNORE_NEW_LINES);

// Group name
$group = '????';

// Our result
$GroupsAndNames = array();

// Loop over all lines; extract group names and person names
foreach($lines as $line) {
    if (trim($line)=='') continue; // ignore empty lines
    if ( ($line[0]!=' ') && ($line[0]!="\t") ) {
        // it's a group entry, so create an empty group array
        $group = trim($line);
        $GroupsAndNames[$group] = array();
    } else {
        // it's a person's name, so add to group array
        $GroupsAndNames[$group][] = trim($line);
    }
}

echo '<!DOCTYPE html>
<html>
<head>

<title>Boys and Girls</title>

<head>
<style>
    div input + div > div {
    display: none;
    padding-left:24px;
}
div input:checked + div > div {
    display: block;
}
</style>
</head>

<body>' . PHP_EOL;
foreach($GroupsAndNames as $key => $group) {
    echo '    <div>' . PHP_EOL;
    echo '        <label for="'.$key.'">'.$key.'</label>' . PHP_EOL;
    echo '        <input type="checkbox" id="boys" />' . PHP_EOL;
    echo '        <div>' . PHP_EOL;
    foreach($group as $name) {
    echo '            <div>'.$name.'</div>' . PHP_EOL;
    }
    echo '        </div>' . PHP_EOL;
    echo '    </div>' . PHP_EOL;
}
echo '
</body>
</html>
' . PHP_EOL;
?>

This produces the HTML page as in your question.

Note: Of course, you need to modify the $filename filename.

Upvotes: 2

Related Questions