File And Directory Manipulation In PHP (part 2) - Fertile Fields (
Page 3 of 13 )
In addition to the simple fgets() function, PHP also offers the
more-sophisticated fgetcsv() function, which not only reads in data from a file,
but also parses each line and, using the comma (,) symbol as delimiter, splits
the data on each line into fields for further processing. The return value from
every call to fgetcsv() is an array containing the fields found.
An example might make this clearer. Consider the following CSV file,
john,67,John Doe,India
sue,32,Sue Me,New York
sarah,10,Sarah Whu,Korea
ramu,23,R Amulet,London
and this PHP script, which reads it and displays the information within it as
an XML document:
<?php
// open XML tags
echo "<?xml version='1.0'?>";
echo "<collection>";
// set file to read
$filename = "users.txt";
// open file
$fh = fopen ($filename, "r") or die("Could not open file");
// read file
while (!feof($fh))
{
// create XML structure
echo "<user>";
$fields = fgetcsv($fh, 1000);
echo "<username>" . $fields[0] . "</username>";
echo "<fullname>" . $fields[2] . "</fullname>";
echo "<age>" . $fields[1] . "</age>";
echo "<city>" . $fields[3] . "</city>";
echo "</user>";
}
// close file
fclose ($fh);
echo "</collection>";
?>
In this case, the comma-separated values in the input file are automatically
parsed into an array, and can then be processed, or reassembled in any order you
like, to create different output. Here's what the script above results in:
<?xml version='1.0'?>
<collection><user><username>john</username><fullname>
John
Doe</fullname><age>67</age><city>India</city>
</user><user><username>sue</use
rname><fullname>Sue
Me</fullname><age>32</age><city>New
York</city>
</user><user><username>sarah</username><fullname>
Sarah
Whu</fullname><age>10</age><city>Korea</city>
</user><user><username>ramu</us
ername><fullname>
R
Amulet</fullname><age>23</age><city>London</city>
</user></collection>