使用php列出文本文件中的数据
I am using a text file as a database. This code only shows the row by the id I select. I want it to show everything from the text file.
<?php
$lines = file('database.txt');
$data = array();
$id = 1;
for($i = 0; $i < count($lines); $i++){
if($lines[$i] == $id){
$data[0] = $lines[$i];
$data[1] = $lines[$i+1];
$data[2] = $lines[$i+2];
$data[3] = $lines[$i+3];
}
}
?>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
<title>Test</title>
</head>
<body>
<div class="box1">
<h1><?= $data[1]; ?></h1>
<img src="<?= $data[2]; ?>">
<p>
<?= $data[3]; ?>
</p>
<br />
<a href="<?= $data[4]; ?>">Click here!</a>
</div>
<div class="box1">
<h1><?= $data[1]; ?></h1>
<img src="<?= $data[2]; ?>">
<p>
<?= $data[3]; ?>
</p>
<br />
<a href="<?= $data[4]; ?>">Click here!</a>
</div>
</body>
</html>
and here is my database file
1
Name
Image
My text
Link
-------
2
Name1
Image1
Text1
Link1
-------
3
Name3
Image3
Text3
Link3
-------
First to answer your question
I don't know if you want to display everything at once, or just a table of contents type of deal, so here goes the former and I will edit my post if you need the latter
EDITED: added trim
in the if
clause to build the array properly and in the print function to eliminate new-lines.
a. show everything
<?php
$lines = file('database.txt');
$i=0;
foreach ($lines as $line){
if (trim($line)!="-------") $data[$i][]=$line;
else $i++;
}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
<title>Test</title>
</head>
<body>
<?php
foreach ($data as $key=>$val) {
print '<div class="box'.$key.'">
<h1>'.trim($val[1]).'</h1>
<img src="'.trim($val[2]).'">
<p>'.trim($val[3]).'</p>
<br />
<a href="'.trim($val[4]).'">Click here!</a>
</div>';
}
?>
</body>
</html>
Next I suggest you store your information in CSV format, like this:
Name,Image,Text,Link
Bob,/home/images/bob.jpg,"some text",http://bob.example.com
Alice,/home/images/alice.png,"alice is wonderfull",http://alice.org
Then you can easily parse the csv file using fgetcsv
http://php.net/manual/en/function.fgetcsv.php
You're overcomplicating things. This is the skeleton of all you'd need to do:
<body>
blah blahblah
<?php
$data = file('database.txt');
foreach($data as $line) {
echo $line[0];
}
?>
</html>
</body>
try this
$data = file('database.txt');
for($i = 0; $i < count($data); $i++){
print_r($data[$i]);
}