[英]How to display definition list from text file using php
I have a definition list of movie credits in a text file. 我在一个文本文件中有电影学分的定义列表。 I used a
preg_split
to read and separate the file with the following line: 我使用
preg_split
读取并通过以下行分隔文件:
$infoLines= preg_split( "/\\n|:/", file_get_contents(getPath($dir,"info.txt")));
I need to display the contents of this file with each even numbered index will have a <dt>
tag while every odd numbered index will have a <dd>
tag. 我需要显示此文件的内容,每个偶数索引将具有
<dt>
标记,而每个奇数索引将具有<dd>
标记。 I am trying to do this by using a foreach loop. 我正在尝试通过使用foreach循环来做到这一点。
I found a tutorial site with the following example 我找到了一个带有以下示例的教程站点
$movie = array( "title" => "Rear Window",
"director" => "Alfred Hitchcock",
"year" => 1954,
"minutes" => 112 );
echo "<dl>";
foreach ( $movie as $key => $value ) {
echo "<dt>$key:</dt>";
echo "<dd>$value</dd>";
}
echo "</dl>";
Which prints: 哪些打印:
title:
Rear Window
director:
Alfred Hitchcock
year:
1954
minutes:
112
I tried to incorporate something like this into my code and I couldn't get it to work since I am reading from a file and not setting the array/key manually. 我试图将类似的内容合并到我的代码中,但是由于我正在从文件中读取并且未手动设置数组/键,因此无法正常工作。
function DisplayInfo($dir){
$infoLines= preg_split( "/\n|:/", file_get_contents(getPath($dir, "info.txt")) );
echo "<dl>";
foreach ($infoLines as $key => $value) {
echo"<dt>$key</dt>";
echo"<dd>$value</dd>";
}
echo "</dl>";
}
My output is: 我的输出是:
0
STARRING
1
Cary Elwes, Robin Wright, Andre the Giant, Mandy Patinkin
2
DIRECTOR
3
Rob Reiner
But I need: 但是我需要:
STARRING
Cary Elwes, Robin Wright, Andre the Giant, Mandy Patinkin
DIRECTOR
Rob Reiner
I feel like I am almost there and have just hit a dead end. 我觉得自己快要死了,已经走到了尽头。 How can I properly display definition lists in PHP?
如何在PHP中正确显示定义列表?
There are plenty of examples such as the one I posted but none dealing with information from txt files. 有很多示例,例如我发布的示例,但没有一个示例处理txt文件中的信息。
Based on your code I'm assuming a line in your file looks something like 根据您的代码,我假设文件中的一行看起来像
DIRECTOR:Rob Reiner
In which case, you shouldn't be splitting the line data until you are ready to print. 在这种情况下,在准备打印之前,请勿拆分行数据。
function DisplayInfo($dir){
$infoLines= file(getPath($dir, "info.txt"));
echo "<dl>";
foreach ($infoLines as $line) {
list($key, $value) = explode(':', $line, 2);
echo"<dt>$key</dt>";
echo"<dd>$value</dd>";
}
echo "</dl>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.