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:
$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. I am trying to do this by using a foreach loop.
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?
There are plenty of examples such as the one I posted but none dealing with information from txt files.
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>";
}
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.