Parsing a File: fscanf


Parsing a File: fscanf

To make it easier to extract data from a file, you can format that file (using, for example, tabs) and use fscanf to read your data from the file. Here's how you use fscanf in general:

 fscanf (resource handle, string format) 

This function takes a file handle, handle, and format, which describes the format of the file you're working with. You set up the format in the same way as with sprintf, which was discussed in Chapter 3, "Handling Strings and Arrays." For example, say the following data was contained in a file named tabs.txt, where the first and last names are separated by a tab:

 George        Washington Benjamin      Franklin Thomas        Jefferson Samuel        Adams 

Reading this kind of file with fscanf is easy. Start by opening the file:

 <?php     $handle = fopen("tabs.txt", "rb");         .         .         . ?> 

The format in this case is "%s\t%s\n" (string, tab, string, newline character), so here's how we read and parse a line of data from a file into an array named $names:

 <?php     $handle = fopen("tabs.txt", "rb");     while ($names = fscanf($handle, "%s\t%s\n")) {         .         .         .     } ?> 

That array can be dissected using the list function:

 <?php     $handle = fopen("tabs.txt", "rb");     while ($names = fscanf($handle, "%s\t%s\n")) {         list ($firstname, $lastname) = $names;         .         .         .     } ?> 

And we can echo the results as shown in phpfscanf.php, Example 7-10.

Example 7-10. Using fscanf, phpfscanf.php
 <HTML>     <HEAD>         <TITLE>             Reading a file with fscanf         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Reading a file with fscanf             </H1>             <?php                 $handle = fopen("tabs.txt", "rb");                 while ($names = fscanf($handle, "%s\t%s\n")) {                     list ($firstname, $lastname) = $names;                     echo $firstname, " ", $lastname, "<BR>";                 }                 fclose($handle);             ?>         </CENTER>     </BODY> </HTML> 

That's all it takes; you can see the results in Figure 7-10.

Figure 7-10. Reading from a file using fscanf.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net