HomePHP Page 3 - File And Directory Manipulation In PHP (part 2)
Fertile Fields - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
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");
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: