Read and Split text file with PHP

Hi there, recently one of my client ask for a script, that is he has a text file containing about 100000 lines. Now he needs to split those files into several files. In this tutorial I am going to describe about the simple script. After complete this script you can do the followings with it:

  • Browse a text file containing a lot of lines
  • Provide number of lines to extract in new files

Step-1:

Let’s create a web form in a PHP file, by which we can browse a text (.txt) file. You can use the below code:

 
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Split Text File Form</title>
<style type=”text/css”>
body {
width:100%;
margin:0;
padding:0;
font-family:helvetica,verdana,sans-serif;
color:#121212;
font-size:1em;
background:#eeeeee;
}
.clr {
clear: both;
}
.part {
-moz-border-radius: 5px 5px 5px 5px;
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #CCCCCC;
font-size: 1.05em;
line-height: 1.5em;
padding: 10px;
max-width:600px;
margin: 0 auto;
}
.label {
float:left;
width:8em;
}
</style>
</head>

<body>
<div class=”part”>
<div class=”part”>
<form action=”” method=”post” enctype=”multipart/form-data”>
<div class=”clr”>
<div class=”label”>
<label for=”tp_file” title=”Browse a text File”>Browse File</label>
</div>
<input type=”file” name=”tp_file” id=”tp_file” />
</div>
<div class=”clr”>
<div class=”label”>
<label for=”line_no” title=”Total Line Number to extract in a File”>Line Number</label>
</div>
<input type=”text” name=”line_no” id=”line_no” />&nbsp;
<input type=”submit” name=”submit” value=”submit” />
</div>
</form>
</div>
</div>
</body>
</html>

This will create a web form exactly like the below image.

file browse form

Step-2:

Now we need to add some PHP script to process our request. We will add the PHP script in the previous page (“index.php”). Check the below PHP Code:

<?php
if(isset($_POST[‘submit’])) {

if ($_FILES[“tp_file”][“error”] > 0) {
echo “Error: ” . $_FILES[“tp_file”][“error”] . “<br />”;
} else {
$line_no = empty($_POST[‘line_no’]) ? 500 : $_POST[‘line_no’];
$file_loc = $_FILES[“tp_file”][“tmp_name”];
$file=fopen($file_loc,”r”) or exit(“Unable to open file!”);

$total_line_no = 0;//COUNTING TOTAL LINE NUMBER
$file_content = “”;//STORING TEXT DATA TEMPORARY
$file_no = 0;//COUNTING FILES CREATED

while (!feof($file)) {
$demo_data = fgetc($file);
if($demo_data==”\n”) {
$file_content .= $demo_data;
$total_line_no = $total_line_no+1;

if($total_line_no%$line_no==0) {
$file_no = $file_no+1;
$tp_file_name = “file_no_”.$file_no.”_with_last_line_”.$total_line_no.”.txt”;
$result = writeData($tp_file_name, $file_content);
echo $result.”<br />”;
$file_content = “”;
}

} else {
$file_content .= $demo_data;
}
}
fclose($file);
}
}
function writeData($myFile, $stringData) {
$file_full_path = ROOT_FOLDER . “/output/” .$myFile;//Defined new file path in the output folder of root directory.
$isFileExist = file_exists($file_full_path);

$fh = fopen($file_full_path, ‘w’) or die(“can’t open file”);
fwrite($fh, $stringData);
fclose($fh);

if($isFileExist) {
return “File: $myFile replaced at ‘” . ROOT_FOLDER . “/output’ Location.”;
} else {
return “File: $myFile created at ‘” . ROOT_FOLDER . “/output’ Location.”;
}
}
?>

 

Here are some descriptions of the above code:

if(isset($_POST[‘submit’])) {  

Above condition enable the script not to execute without submit the form.

 

$line_no = empty($_POST[‘line_no’]) ? 500 : $_POST[‘line_no’];

Get the line number from web page form. If blank given 500 line by default.

 

$file=fopen($file_loc,”r”) or exit(“Unable to open file!”);

The fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. The first parameter of this function is the file to be opened and the second parameter specifies in which mode the file should be opened. The modes in which the file can be opened are listed below:

Modes

Description

r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already

 

Note that if the fopen() function is unable to open the specified file, it returns 0 (false).

 

while (!feof($file)) {

Running a while loop by checking if the content of file not come to the end.

 

$demo_data = fgetc($file);

fgetc used to get a string containing a single character from the given parameter of file pointer.

 

if($total_line_no%$line_no==0) {

If reached the number of lines to store each files.

 

$result = writeData($tp_file_name, $file_content);

Calling writeData() function to create or replace (if exist with same name) file. The writeData() need two parameter – text file path and the data to be written.

 

$isFileExist = file_exists($file_full_path);

file_exists function return boolean. It return true if the file is exist as given in the parameter, otherwise false.

Now it’s time to check the code in your server. Download the PHP Script.  Cheers!!!

 

Author Info

Shah Alom

Hi, This is Mohammad Shah Alom, My passion is Programming & Web Development. I am Founder of Micro Solutions Bangladesh. My Facebook profile shahalom1983 & Twitter Profile shahalom_83