php read and extract data from text file - php

This is to upload and print a text file. Now, this txt file contains details of people booking and comes via email and looks something like this:
some text (always the same)
= ================
text again
name : Mr F Someone
address: Somewhere
...
...
more same text
The problem is there are no delimiters. and I want to grab the data like "Mr", "F", "Someone",... and then put each one of them in an input field of a form. I tried something like this:
$section_a = file_get_contents($up_folder, NULL, NULL, 508, 2);
echo '<input type="text" name="Title" value="'.$section_a.'">';
but if it is "Miss" instead of "Mr" then it is a problem, same as the length of the name and so on. And there is more than one "booking" in a file. So, is there a way of getting the details of each booking out of the file to put each time in a form?
<?php
if($_FILES['userfile']['error'] > 0){
echo 'Houston, we have a problem: ';
switch($_FILES['userfile']['error'])
{
case 1: echo 'file too big'; break;
case 2: echo 'file too big'; break;
case 3: echo 'incomplete upload'; break;
case 4: echo 'uplad error'; break;
}
exit;
}
if($_FILES['userfile']['type'] != 'text/plain'){
echo 'Ooh noes! File is not plain text dude!';
exit;
}
$up_folder = 'upload/'.$_FILES['userfile']['name'];
if(is_uploaded_file($_FILES['userfile']['tmp_name'])){
if(!move_uploaded_file($_FILES['userfile']['tmp_name'], $up_folder)){
echo 'cannot move file';
exit;
}
}
else{
echo 'error: ';
echo $_FILES['userfile']['name'];
exit;
}
echo 'file upload successful<br>';
$fp = fopen($up_folder, 'r');
$contents = fread($fp, filesize($up_folder));
fclose($fp);
$contents = strip_tags($contents);
$fp = fopen($upfile, 'w');
fwrite($fp, $contents);
fclose($fp);
echo 'Uploaded file content: <br> <br>';
echo $contents;
?>

$fetch = ['name','address'];
$output = [];
$fp = fopen($file, 'r');
while(!feof($fp) && count($output) !== count($fetch)) {
$line = fgets($line);
list($prefix, $value) = explode(':', $line, 2);
$prefix = strtolower(trim($prefix));
foreach($fetch as $f) {
if($prefix === $f) {
$output[$f] = trim($value);
break;
}
}
}
fclose($fp);
print_r($output);

Related

How to check for duplicate content in txt file?

I have a .txt file which contains objects on each line.Meaning the first line is "baby",second line "toddler",next line "dog" and the line after is "cat".
I want to be able to add objects into my txt file using php but i want to prevent duplicates.Somehow my codes only work for "dog".When i try to add "dog" it will say this object already exist but when i try "cat" / "baby" /"toddler" it still adds even though it is already in the list.
CODES
$check = false;
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
$check = true;
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_lines = file('lbls/predefined_classes.txt');
foreach($file_lines as $line){
if($_POST['addLbl'] === $line){
$check = true;
}
}
if($check === false){
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
Txt File Content
because you add list manualy and have white space in the end of each line add trim() function solve problem
<?php
$check = false;
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
$check = true;
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_lines = file('lbls/predefined_classes.txt');
foreach($file_lines as $line){
if($_POST['addLbl'] === trim($line)){ // trim() added here
$check = true;
}
}
if($check === false){
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
}
?>
output test for cat :
The label cat already exists.
try the following, little shorter with same logic. No need for $check among other improvements.
if(isset($_POST['add'])){
if($_POST['addLbl'] == ''){
echo ' Please enter a label';
}
else{
$data = "\r\n".$_POST['addLbl'];
$file_str = file_get_contents('lbls/predefined_classes.txt');
if (!strrpos ( $file_str , $data)) { // not found
$ret = file_put_contents('lbls/predefined_classes.txt',$data,FILE_APPEND | LOCK_EX);
if($ret === false){
echo ' Unable to add.An error occurred.';
}
else{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}else{
echo 'The label '.$_POST['addLbl'].' already exists.';
}
}
}
The $file_lines array looks like as below
array
(
[0] => \r\n
[1] => baby\r\n
[2] => toddler\r\n
[3] => cat\r\n
[4] => dog
)
You must remove next line escape sequence(i.e,\r\n) from $line and then compare with $_POST['addLbl']
You get lines with the new line character. Read the file and split it into lines.
$newline = PHP_EOL; // your editor might use another new line character
if(in_array($_POST['addLbl'], explode($newline, file_get_contents('test.txt'))))
// echo error message
else
// append to file
The entire task can be done in a few lines. Btw. check also for unset $_POST entries.
if(isset($_POST['add']))
{
if(!isset($_POST['addLbl']) || $_POST['addLbl'] === '')
echo ' Please enter a label';
elseif(in_array($_POST['addLbl'], explode(PHP_EOL, file_get_contents('lbls/predefined_classes.txt'))))
echo "The label {$_POST['addLbl']} already exists.";
elseif(false === file_put_contents('lbls/predefined_classes.txt',PHP_EOL . $_POST['addLbl'], FILE_APPEND | LOCK_EX))
echo ' Unable to add.An error occurred.';
else
{
echo ' Sucessfully added!';
$_POST['addLbl'] = '';
}
}

PHP - Display differences between two CSV files

I have written a small script which upload two csv files and compare them.
//set files upload directory
$target_dir1 = "uploads/old/";
$target_file1 = $target_dir1 . basename($_FILES["fileToUpload1"]["name"]);
$target_dir2 = "uploads/new/";
$target_file2 = $target_dir2 . basename($_FILES["fileToUpload2"]["name"]);
$uploadOk = 1;
//Upload files
if ($uploadOk == 0) {
echo "<BR> Sorry, your files were not uploaded. <BR>";
} else {
if (move_uploaded_file($_FILES["fileToUpload1"]["tmp_name"], $target_file1)) {
echo "<BR> The 1st file ". basename( $_FILES["fileToUpload1"]["name"]). " has been uploaded. <BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 1st file. <BR>";
}
if (move_uploaded_file($_FILES["fileToUpload2"]["tmp_name"], $target_file2)) {
echo "<BR> The 2nd file ". basename( $_FILES["fileToUpload2"]["name"]). " has been uploaded.<BR>";
} else {
echo "<BR> Sorry, there was an error uploading your 2nd file. <BR>";
}
}
//Get contetnt 1st file
$table1 = Array();
$filehandle1 = fopen($target_file1, "r") ;
if($filehandle1 !== FALSE) {
while(! feof($filehandle1)) { // feof end of file
$data1 = fgetcsv($filehandle1, 1000, ",");
array_push($table1, $data1);
}
}
fclose($filehandle1);
//Get content 2nd file
$table2 = Array();
$filehandle2 = fopen($target_file2, "r") ;
if($filehandle2 !== FALSE) {
while(! feof($filehandle2)) {
$data2 = fgetcsv($filehandle2, 1000, ",");
array_push($table2, $data2);
}
}
fclose($filehandle2);
//Find difference between these two files
$headers= array();
$headers = $table1[0];
$i= 0;
foreach ($table1 as $table) {
echo '<BR>';
$diff = array_diff($table2[$i], $table);
if(!empty($diff)) {
print_r($diff);
$chiave= key($diff);
echo $headers[$chiave];
};
echo '<BR>';
$i++;
}
And this is the error I get, however difference between the two files are dispalyed correctly:
Warning: array_diff(): Argument #1 is not an array in /var/www/csv_files/upload.php on line 67 Call Stack: 0.0053 337384 1. {main}() /var/www/csv_files/upload.php:0 0.0064 367220 2. array_diff() /var/www/csv_files/upload.php:67
You get this error because the first argument is not a array where one is expected. You are now checking a table with the nth element of a array but not the whole array. I think you are making a mistake in thinking table2 is a 2 dimensional array, and it's not. It is used a one dimensional array with nth data2 elements.
Hope this helps!
Seems yes, sometimes table2 is empty or those CSV files have different amount of rows - as result that warning.
So - you need add extra checks if $table2[$i] is not null.
Just a bit another variant from me - how to read file faster (Get content 1st and second file):
$table1 = file($target_file1);
$table2 = file($target_file2);
And then you can do same things as before, with extra tests:
if (count($table1)) {
$headers = str_getcsv($table1[0]);
foreach ($table1 as $key => $table) {
if (!isset($table2[$key])) {
echo 'Row ' . ($key+1) . ' is not exists in second CSV file.';
} else {
$diff = array_diff(str_getcsv($table2[$key]), str_getcsv($table));
// Here is code as in your example
print_r($diff);
$chiave = key($diff);
echo $headers[$chiave];
}
}
}
Good luck! :)

if TXT empty echo message possible?

Hi I have a piece of code that is able to delete each newline in a txt file. Now my question is if the txt file is empty it gives an error message that $line doesn't exist. Now i want to add a piece off code that if txt has no content it echo's a message like "no emails in the list"
<?php
$delete = #$_GET['delete'];
$textFile = file("../emaillist/emaillist.txt");
$lines = count($textFile);
if($delete != "" && $delete >! $lines || $delete === '0') {
$textFile[$delete] = "";
$fileUpdate = fopen("../emaillist/emaillist.txt", "wb");
for($a=0; $a<$lines; $a++) {
fwrite($fileUpdate, $textFile[$a]);
}
fclose($fileUpdate);
echo"<p class='accept'>Contact verwijderd!</p>";
exit;
}
foreach($textFile as $key => $val) {
$pre= "<label style='float:left;' class='tablog3a'>";
$line = #$line . $pre . $val . "</label><a style='float:right;' href =?delete=$key><img class='clickreverse' src='images/deletetodo.png'></a><br>";
}
echo $line;
?>
I allready tried:
else {
echo "no emails in the list";
}
but that gave nothing....
I can think of a few ways to check if a file is empty:
$textfile = file('text.txt');
$lines = count($textfile);
if (empty($lines))
echo 'file is empty';
Or:
if (filesize('text.txt') === 0)
echo 'file is empty';
Or, if you want to check if it is empty, not including blank lines or extra whitespace:
$textfile = trim(file_get_contents('text.txt'));
if (empty($textfile))
echo 'file is empty';

Issue with array in php

my scenerio is:
A user want to check if the specific(client) url is present in destination url or not and I have created simple script to test the specific url in one destination url.
Here is my php script:
if(isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$contents = file_get_contents($destination_url);
$search = $client_url;
if(strpos($contents,$search)== FALSE)
{
echo "Not Found";
}
else
{
echo "Found";
}
}
Here is my html script:
<form method="post" action="test.php">
<label>Client URL:</label>
<input type="text" value="" name="client_url" /><br />
<label>Destination URL:</label>
<textarea value="" name="destination_url" ></textarea><br />
<button type="submit" name="check_url">Check</button>
</form>
The above script is working in case of single destination url but when I tried to post multiple destination url(by converting it into array) I'm getting the error:
Warning: file_get_contents( http://learntk12.org/story.php?title=seo-link-building-service) [function.file-get-contents]: failed to open stream: No such file or directory in "path to source file" on line 24
where line 24 is: $contents[$i] = file_get_contents($arr[$i]);
Here is my php code with array:
if(isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$destination =str_replace("\r",",",$destination_url);
$arr = explode(",",$destination);
$search = $client_url;
for($i=0;$i<count($arr);$i++)
{
$contents[$i] = file_get_contents($arr[$i]);
if (strpos($contents[$i], $search) === FALSE)
{
echo "Not Found";
}
else
{
echo "Found";
}
}
}
Where am I lagging in this script?
Try this:
if (isset($_POST['check_url']))
{
$client_url = $_POST['client_url'];
$destination_url = $_POST['destination_url'];
$destinations = str_replace(array("\r\n", "\n"), ',', $destination_url); // replace both types of line breaks with a comma, \r alone will not suffice
$destinations = explode(',', $destinations); // split at commas
foreach ($destinations as $destination) // loop through each item in array
{
$contents = file_get_contents($destination); // get contents of URL
echo (FALSE === strpos($contents, $client_url)) // check if remote data contains URL
? 'Not Found' // echo if TRUE of above expression
: 'Found'; // echo if FALSE of above expression
}
}
As far as I see you don't have an array $contents. It should work like this:
$contents = file_get_contents($arr[$i]);
if (strpos($contents, $search) === FALSE) {
echo "Not Found";
} else {
echo "Found";
}

A peculiar newbie debugging

It is one of the things I should have the know how but it really bugs. I have a large script which automates several tasks. It starts with uploading of files after which data from the files are extracted and then imported into mysql. In debugging mode it works perfectly but on my web front-end, execution stops after the data from the uploaded file is extracted. It never reaches the importation into database phase.
I realised that I had used this particular code below which I hold suspect:
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if($inFileName != "")
$inputFile = fopen($newFilePath,"r");
else exit(1);
if(!$inputFile)
exit(0);
while(!feof($inputFile)) {
It is obvious that the exit() as used terminates the scripts thereby leaving out the lines that is handling the import of data into mysql.WIth the above, the upload works and the data separation carried out but the import never got executed. After some study I reviewed that portion by doing something quite appropriate like:
if (file_exists($inFileName)){
$inputFile = fopen($newFilePath,"r");
}
else {
echo "No file found ";
}
if (is_readable($inputFile)){
echo " ";
}else {
echo 'The file could not be read';
}
Now this piece of code review did not get me anyway as the upload is not even possible.
Now my problem is to fix this little portion of the code so I get the other parts of the script after it to do the import. It has been a nightmare for a beginner like me. I would appreciate if someone could review the above portion in a different way. I hope to see something that is similar or different but valid. I have learnt tougher stuff than this but this is simply nuts. I hope someone could understand my explanation. Thanks
New Edit.
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
}
} else {
echo "File not accessable";
}
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
Entire Script
<?php
#This script has threee parts: The first handles the uploaded files while the second part retrieves all RMCs and Handover dates and the 3rd handles importation of the data into their respective table in mysql database.
# This part uploads text files
include 'setamainfunctions.php';
if (isset($_POST['uploadfiles'])) {
$number_of_uploaded_files = 0;
$number_of_moved_files = 0;
$uploaded_files = array();
$upload_directory = dirname(__file__) . '/Uploads/';
//echo count($_FILES['uploadedFile']['name'])." uploaded ";
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') { //check if file field empty or not
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
echo "Number of files submitted $number_of_uploaded_files . <br/>";
echo "Number of successfully moved files $number_of_moved_files . <br/>";
echo "File Names are <br/>" . implode("<br/>", $uploaded_files)."\n";
echo "</br>";
echo "<p> Please find the processed RMCs and corresponding handovers as text files named:outputRMCs.txt and OutputHandovers.txt in the Setapro project root folder</p>";
/* echo "<br/>";
echo "<br/>";
echo "<p> Result of Mobile GPRMCs Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and import mobile mobile GPRMCs successfuly completed";
echo "<br/>";
echo "<br/>";
echo "<p> Result of Handover Transaction";
//echo "Total entries imported:.$numlines . <br/>";
echo "Data extraction and imports for mobile handovers successfuly completed";*/
}
# This is the start of a script which accepts the uploaded into another array of it own for extraction of GPRMCs and handover dates.
$searchCriteria = array('$GPRMC');
//creating a reference for multiple text files in an array
/*if(isset($_FILES['uploadedFile']['name']))
$_FILES['uploadedFile'] = '';
}else {
echo "yes";
}*/
$inFilesArray = ($_FILES['uploadedFile']['name']);
//$inFiles = fopen($_FILES['uploadedFile']['tmp_name'], 'r');
//This opens a textfile for writing operation and puts all the entries from the multiple text files into one distinct textfile
if( ($outFile4 = fopen("outputRMCs.txt", "a")) === false ){
echo " ";
}
$outFile5 = fopen("outputHandovers.txt", "a");
//processing individual files in the array called $inFilesArray via foreach loop
if (is_array($inFilesArray)) {
foreach($inFilesArray as $inFileName) {
$numLines = 1;
$newFilePath = $upload_directory."/".$inFileName;
$correctFile = false;
//opening the input file
if (file_exists($newFilePath)){
if (is_readable($newFilePath)){
$inputFile = fopen($newFilePath,"r");
$correctFile = true;
}
}
if (!$correctFile)
echo "File not accessable";
//reading the inFile line by line and outputting the line if searchCriteria is met
while(!feof($inputFile)) {
$line = fgets($inputFile);
$lineTokens = explode(',',$line);
// Assign Device ID
switch ($lineTokens[0]){
case "IMEI 358998018395510\r\n":
$device_id = 1;
break;
case "IMEI 352924028650492\r\n":
$device_id = 3;
break;
case '$GPVTG':
$device_id = 2;
break;
}
if(in_array($lineTokens[0],$searchCriteria)) {
if (fwrite($outFile4, $device_id . "," .$line)===FALSE){
echo "Problem writing files\n";
}
$time = $lineTokens[1];
$date = $lineTokens[9];
$numLines++;
}
// Defining search criteria for $GPGGA
$lineTokens = explode(' ',$line);
$searchCriteria2 = array('OutCell');
if(in_array($lineTokens[0],$searchCriteria2)) {
if (fwrite($outFile5, $time.",".$date."\n")===FALSE){
echo "Problem writing to file\n";
}
}
}
fclose($inputFile);
}
//close the in files
fflush($outFile4);
fflush($outFile5);
}
fclose($outFile4);
fclose($outFile5);
#End of script for handling extraction
# This is the start of the script which imports the text file data into mysql database and does the necessary conversion.
$FilePath1 = $_SERVER["DOCUMENT_ROOT"] . '/setapro/outputRMCs.txt';
if (is_readable($FilePath1)) {
$handle = fopen($FilePath1, "r");
rmc_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#Begining of script to handle imports into handover table
$FilePath2 = $_SERVER["DOCUMENT_ROOT"].'/setapro/outputHandovers.txt';
if (is_readable($FilePath2)) {
$handle = fopen($FilePath2, "r");
mobile_handoverHandler($handle);
echo "";
fclose($handle);
} else {
echo 'The file could not be read';
}
#End of script for handling imports into handover table
?>
It seems to me you want to do something more like this...
$newFilePath = $upload_directory."/".$inFileName;
$goodFile=false;
//Does the file exist?
if (file_exists($newFilePath)){
//If so, is it readable?
if (is_readable($newFilePath)){
//if it exists, and it readable, open it
$inputFile = file_get_contents($newFilePath);
//Don't display the error when done because file is good
$goodFile=true;
//Do Other stuff with file contents
}
}
if (!goodFile) echo "File Access Error";
You want to use newFilePath as it contains the path as well as the file name. The fact that you are checking for the file's existence and readability without also passing the file's path (only the file name) may be the cause of your issues.
UPDATE
try {
for ($i = 0; $i < count($_FILES['uploadedFile']['name']); $i++) {
//$number_of_file_fields++;
if ($_FILES['uploadedFile']['name'][$i] != '') {
$number_of_uploaded_files++;
$uploaded_files[] = $_FILES['uploadedFile']['name'][$i];
//if (is_uploaded_file($_FILES['uploadedFile']['name'])){
if (move_uploaded_file($_FILES['uploadedFile']['tmp_name'][$i], $upload_directory . $_FILES['uploadedFile']['name'][$i])) {
$number_of_moved_files++;
}
}
}
} catch (exception $e){
echo "General Error";
}

Categories