Tutorial - PHP - Read/Write Files


Coding Friends Tutorial Index - > PHP

Author Ian - Tutorial Posts = 62
This is a tutorial on how to open and write files with PHP, of course there is always different ways to accomplish the same task within programming languages.

Fopen will open up a file, the secod parameter is who to open the file, r = read, w = write.
$readin = fopen("countrys.txt", "r");

The while loop will set the variable $county equal to a line from the input file, the fscanf will scan a file with the second parameters requirements, the “%[^\n]” means anything that is not(^) a return character (\n).
while ($county = fscanf($readin, "%[^\n]")) {

Fwrite will output to the output file handler (the $output created with fopen), with the text in the second parameters
fwrite($output, "insert into country(place) values (\"$county[0]\");\n");

NOTE: the { } are the begin and end of a code structure, e.g. While begin; do something; end;

This is the code
---
<?php
       $readin = fopen("countrys.txt", "r");
       $output = fopen("sqlcountrys.txt", "w");
       
       while ($county = fscanf($readin, "%[^\n]")) {
              echo $county[0]. "\n";
              fwrite($output, "insert into country(place) values (\"$county[0]\");\n");
       }
       fclose($readin);
       fclose($output);
?>
---
if you save that as phpreadfile.php. and also create a countrys.txt file with what ever text you like, e.g. United Kingdom
France
Germany
United States etc.

The output of the program (php phpreadfile.php) will display each line that is read from the input file and the output file will have some other text in it, for demonstrating purposes, have done some sql code.

I have attached the code and also the countrys.txt file.
Creation of cool tutorials :)
User Name Password
Copyright@CodingFriends, 2005-2006. All Rights Reserved.
Home | Forums | Tutorials | Users
RSS Feeds - Global Global CodingFriends RSS Feed - Tutorials Tutorials CodingFriends RSS Feed - Forums Forums CodingFriends RSS Feed - News News CodingFriends RSS Feed
Users
Login|Password problem| Register here

Tutorials
Tutorials Home| C/C++| C#/Mono| Java| Javascript| PHP| Ruby| SQL| (X)HTML/CSS| VB| Linux| Windows

Forum
Forum Home

Projects
3D Game

Site
Home| About me| Links| FAQ

Search