简体   繁体   中英

reading content from multiple files into array php

I am struggling with this problem i can't solve.

i have a sequential text file with the following records structured like this:

    First Name : ......;
    Last Name: ......;
    Contact Details:.....;
    Email Address:.....;
    Enquirer Type:.....;
    Contact Method:....;
    Message:....';
    |----------|
    First Name : ......;
    ..............

I am having trouble displaying the information in a table within the container

        <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" type="text/css" href="styles/session_Style.css">
    <title>User Session</title>
  </head>
  <body>
    <div class="container">

      <div id="table">
      <?php

$filename = "Contacts.txt";
$content = file_get_contents($filename);
$fileContent = explode('|----------|', $content);

foreach ($fileContent as $number => $contact) {

  echo '<table>';
  echo '<tr><th colspan="2">Contact '.$number.'</th></tr>';

  foreach ($contact as $detail) {
    $detail = explode(':',$detail);
    echo '<tr><td>'.$detail[0].'</td><td>'.$detail[1].'</td></tr>';
  }
  echo '</table>';
}
?>
      </div>      
      <div class="logout">
        <h1>User Details</h1>
        <form method="post" action="">
          <p class="submit"><input type="submit" name="commit" value="Log Out" onclick="document.location.href='home-page.html';"></p>
        </form>
      </div>
    </div>
  </body>
</html>

Is this the right way to implement the solutions provided by you guys? Or is there a way it can be done more efficiently?

Try:

$fileContent[$filenumber] = explode(';',file_get_contents($filename));

$fileContent is an array with file numbers as keys. So the data of the file contact_1 will be stored in $fileContent[1]. explode() will make an array with the file contents, separated by the ';'. You can now for example access the first name of contact_2 with $fileContent[2][0]. This will return: "First Name : ....."


Now for the table:

foreach ($fileContent as $number => $contact) {

  echo '<table>';
  echo '<tr><th colspan="2">Contact '.$number.'</th></tr>';

  foreach ($contact as $detail) {

    $detail = explode(':',$detail);
    echo '<tr><td>'.$detail[0].'</td><td>'.$detail[1].'</td></tr>';

  }

  echo '</table>';

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM