简体   繁体   English

从多个文件读取内容到数组php

[英]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. $ fileContent是一个以文件编号作为键的数组。 So the data of the file contact_1 will be stored in $fileContent[1]. 因此,文件contact_1的数据将存储在$ fileContent [1]中。 explode() will make an array with the file contents, separated by the ';'. explode()将创建一个包含文件内容的数组,并以';'分隔。 You can now for example access the first name of contact_2 with $fileContent[2][0]. 现在,您可以使用$ fileContent [2] [0]访问contact_2的名字。 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>';

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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