In: Computer Science
In this assignment you will write a PHP program that reads from a data file, creates an associative array, sorts the data by key and displays the information in an HTML table.
Create a PHP file called hw4.php that will do the following:
- Display your name.
- Read text data from a file. The data file is hw3.txt.
The file hw3.txt will hold the following text:
PQRParrot, Quagga, Raccoon
DEFDo statements, Else statements, For statements
GHIGeese, Hippos, If statements
YZ Yak, Zebra
JKLJelly Fish, Kudu, Lynx
MNOManatee, Nautilus, Octopus
ABCApples, Boas, Cats
VWXVulture, While statements, Xmen
STUSea Horse, Tapir, Unicorn
- Take the first three characters of each line read as the key and
the rest of the line as the value or data.
- Create an associative array with the key and data.- Once all the
data is in the array, sort the array by the key.
- Display the data as an HTML table. Below is what your finished
table should look like.
Key | Data |
ABC | Apples, Boas, Cats |
DEF | Do statements, Else statements, For statements |
GHI | Geese, Hippos, If statements |
JKL | Jelly Fish, Kudu, Lynx |
MNO | Manatee, Nautilus, Octopus |
PQR | Parrot, Quagga, Raccoon |
STU | Sea Horse, Tapir, Unicorn |
VWX | Vulture, While statements, Xmen |
YZ | Yak, Zebra |
- Use repetition to complete this assignment.
Answer:
PHP file called hw4.php
<html>
<head>
<body>
<!-- Display name -->
Name :XZY
<br>
<?php
$fn = fopen("hw3.txt","r");
while(! feof($fn)) {
// getting complete line of the file,
line-by-line
$line = fgets($fn);
// getting first three characters of the line using
function 'substr()'
$field = substr($line, 0, 3);
// getting remaining characters of line after first 3
characters
$data = substr($line, 3);
// Creating an associative array with these
$arr[$field] = $data;
}
fclose($fn);
?>
<?php
// sort the associative array by
key, using function 'ksort()'
ksort($arr);
?>
<!-- Creating a table and
printing array key , value pair in each row -->
<table align="left" border="1"
cellpadding="10" cellspacing="0">
<tr><td>Key</td><td>Data</td></tr>
<?php
foreach ($arr as
$key => $value) {
echo "<tr>";
echo
"<td>".$key."</td>"."<td>".$value."</td>";
echo "</tr>";
}
?>
</table>
</body>
</html>
Screenshot of Output:
-----------------------------------------------------------------------------------------------------------------------------------------