PHP - Loop Through Each Line Of A Text File, Add Code, And Throttle
Here's what I'm trying to do, and I am having trouble getting started with this. It's a very simple process, but I didn't want to spend the next 6 hours in frustration, so some help getting started would be great.
Here's the purpose of the script: 1. Allow user to add a text file to a form. 2. Take the text file, add HTML code to the beginning and end of each paragraph (a single line of text, usually paragraphs would be separated by a line return) 3. Send the user an email with the HTML file attached and thank them or whatever. 4. Allow the system to throttle itself (one-at-a-time) so that many people using the site won't bog it down. These files will probably be anywhere from 100 KB to 1,000 KB in size, usually hitting in the 300-500KB range. Here's what I can do very easily: 1. Allow user to add a text file - very simple and straightforward. 2. Take the text file, add HTML... - this is what I need a little help figuring out. Each paragraph needs to have <p> at the beginning and </p> at the end, and the script will also search for keywords on certain lines (section headers) and add a <align="center"> tag to that, and so forth. I can handle the formatting rules, but making sure the loop runs correctly could be a problem. 3. Send the user an email... - very easy, I can do that myself. 4. Allow the system to throttle itself... - this could be tricky. I was thinking a database with a TINYINT field, 0 for not processed yet, 1 for processing, 2 for processed. Cron job checks the next one on the list to see if it needs to send it to the processor, if the file is already being processed, or can be sent to a different database (completed entries) and removed from the current queue. The cron job would also be responsible for triggering the "Your file is converted!" email and the attachment. Any/all help would be greatly appreciated on this. I am going to work on the parts that I can do myself, and I'll be checking back for the discussion - in between Mountain Dew runs. Similar TutorialsHi, Have a text file that is being read. I want to print the contents however I want each line of the text file to appear on a new line in the browser. So far $str = file_get_contents('records.txt'); $lines = explode("\n", $str); echo $lines[0]; Help appreciated Hi guys, I have script which scraps content from web and writes it down in a text file, now everything seems to be okay. Its scraps and writes well but the problem is when i open that text file one weird character keeps coming after some words which i don't know about. I have attached the text file, will you guys please look at it and tell me how to replace that square looking character into new line in text file. The title says it all,..well as all u can see, there are many methods to accomplish this done but not before undergoing through a heavy tasking process. For instance, 1. Open the file 2. Reads the content of the file into array. 3. Find out the desire line of text that we want to replace. 4. Make that line of text as variable and assigns with the new data(that we want to replace) as its values. 5.open another file. 6.Write the whole contents to the file opened in 5. 7. Put the contents back to the file of original. Can anyone contributes a better way to get this done? Like replace/delete a specific line without affecting other characters or anything therein? Thanx. P.S reading and using str_replace to make the alteration always ends up in giving some kind of result beyond desired after the first round of code execution. I'm ok with PHP but probably not half as good as some of you guys on here. I am basically trying to find a way to grab a line from a huge and I mean huge text file.... its basically a list of keywords I want to call by line number but without preferably going through them all before I get to that line.....otherwise couldmcrash my server obviously. At the moment im using this Code: [Select] $lines = file('http://www.mysite.com/keywords.txt'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) { echo "$line_num"; } This works but im sure theres gotta be a better way of doing to save on usuage because this is putting the whole file into the memory and if I can simply say to php give me line number 97, would umm RULE.... Hope you guys can come up with a solution as your much smarter than me ty This is a section of my code that goes and gets videos from any video site. What I’m having issues with is having it post a random title, that are all in a text file called titles.txt. What I’m wanting to accomplish is have my script go pull the video embed code, the duration, the tags, etc. Which all works fine until I get to the title part where it pulls locally from the server from the text file. I'm not an advance programmer so not sure if I am even approaching this correct way. Here is the code I have that is responsible for putting the title in. I appreciate your help. $video = array( ‘user_id’ => $this->user_id, ‘status’ => $this->status, ‘site’ => ‘my site’, ‘id’ => ‘’, ‘embeddable’ => true, ‘url’ => ‘’, ‘titles’ => ‘’, ‘title’ => ‘’, ‘description’ => ‘’, ‘tags’ => ‘’, ‘category’ => ‘’, ‘thumbs’ => array(), ‘duration’ => 0, ‘embed’ => ‘’ ); function random_title () { $titles = file (“titles.txt”, FILE_IGNORE_NEW_LINES); $num = rand (0, intval (count ($titles) / 3)) * 3; return ucwords($titles[$num]); } //Title if(preg_match(’/title="(.*?)"/’, $match, $matches_title)) { $video[‘title’] = random_title(). ’ - My site name’; } else { $this->errors[] = ‘Failed to get video title for ‘.$video[‘url’].’!’; if (!$this->debug) continue; else $debug_e[] = ‘TITLE’; }
I have a PHP file that is executed via batch file very frequently for live updating. This is a sort of "sync" file for reading/writing to a MySQL database. I am able to get it functioning absolutely fine when executed manually via a web browser (and my echo debug lines output the expected information), yet when I run the same PHP file via the command line, it seems to just not be capable of opening any file for reading, so the equivalent variables that are correct when executed on a web browser are blank when echoed through the command line. Is there a different way of handling reading of files when running a php script via the command line, or should it function exactly the same as when run via a browser? For instance: $k = "0"; $line = file("examplefile.log")[$k]; echo $line; I want my application will send a email after 10 minutes of sending another email. In my application A user completes registration with payment Application sends the user a payment confirmation emailNow I want to send another email 10 minutes After payment confirmation email with welcome tipsBelow is the function where for user setup .
public function finishUserSetup($Sub){ if($Sub == 0){ $subscription = SubscriptionPlans::where('identifier', '=', "Monthly")->first(); $expiry = date('Y-m-d', strtotime('+' . $subscription->months . ' months')); $sub_period = "monthly"; } else{ $subscription = SubscriptionPlans::where('identifier', '=', "Annually")->first(); $expiry = date('Y-m-d', strtotime('+' . $subscription->months . ' months')); $sub_period = "annually"; } $this->expiry_date = $expiry; $this->user_type = "SUB"; $this->subscription_period = $sub_period; $this->update(); $replaceArray = array( 'fullname' => $this->forename . " " . $this->surname, 'subscriptionName' => $subscription->name, ); EmailTemplate::findAndSendTemplate("paymentconfirm", $this->email, $this->forename . " " . $this->surname, $replaceArray); } In the above function the last line of code is the one which sends a payment confirmation email to the user which is EmailTemplate::findAndSendTemplate("paymentconfirm", $this->email, $this->forename . " " . $this->surname, $replaceArray); I want to execute the following line of code 10 minutes after the above one
EmailTemplate::findAndSendTemplate("WelcomeTips", $this->email, $this->forename . " " . $this->surname, $replaceArray);
How to do that. that is running the last line of code 10 minutes after I have a script that reads a .gz file into an array and prints the name of each record but will not work on larger files. Is there a way to read 1 line at a time? Here is the code I have so far. Code: [Select] <?php if ($handle = opendir('.')) { print "<ol>"; while (false !== ($file = readdir($handle))) { if($file != '..' && $file!="." && $file!="start_update.php" && $file!="sharons_dbinfo.inc.php" && $file!="root.php" && $file!="read_directory.php" && $file!="read_dir.php" && $file!="new_category.php" && $file!="index.php" && $file!="file_count.php" && $file!="dir_loop2.php" && $file!="dir_loop1.php" && $file!=".htaccess" && $file!="Answer.txt" && $file!="Crucial_Technology-Crucial_US_Product_Catalog_Data_Feed.txt"){ $filename = $file; $go = filesize($filename); if($go >= 1){ $filename2 = explode("-", $filename); $filename2 = $filename2[0]; echo str_replace("_"," ",$filename2) . ' | Filesize is: ' . filesize($filename) . ' bytes<br>'; $gz = gzopen($filename, 'r'); $lines = gzfile($filename,10000); foreach ($lines as $line) { $line2 = explode(",", $line); $line2 = str_replace("," , "-" , $line2); echo "<li>".str_replace("," , "-" , $line2[4])."</li><br>"; } } } } closedir($handle); } ?> </ol> I'm so sorry to ask such a "newbee question," but believe me I have been on Google for the better part of the week trying to find an answer.
I'll start with the brief question.
Then I'll give an example to show what I mean.
Then, I'll give the BESTEST "pseudo-code" I could come up with (to PROVE that I've really given it my best).
Question:
How do I make PHP loop through a big file, make the changes line by line, and to save the resultant file.
Example: I have a 100mb text file ("animals.txt") with 500,000 lines. If any lines have the word "cat" in it, I want to add "Be careful with cats!" to the end of the line:
From this:
A fish and his tank.
A cat and his toy.
A bird and her cage.
A frog and his lilly.
A cat and her friend.
To this:
A fish and his tank.
A cat and his toy. Be careful with cats!
A bird and her cage.
A frog and his lilly.
A cat and her friend. Be careful with cats!
The best "pseudo-code" I can come up with is:
<?php
$data = file_get_contents("animals.txt");
$lines = explode(PHP_EOL,$data); I have developed the following code, which queries a MySQL database and returns multiple results using several WHILE loops: Code: [Select] <?php # if submit_hash is present, then pull up the attendance from specified hash if($_GET['submit_hash']) { # select all the hashers from the specified hash $query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = " . $_GET['hash_id'] . " && hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id ORDER BY ha.hasher_name "; $result = mysql_query($query) or die('Error selecting Hash attendance.'); $x = 1; while($row = mysql_fetch_array($result)) { if($x == 1) { echo '<strong>' . $row['hash_num'] . ' ' . $row['hash_name'] . ' - ' . date("D, d M Y", strtotime($row['hash_date'])) . '</strong><em>Total Hashers: ' . mysql_num_rows($result) . '</em>'; $x++; } # see if this person was the hare if($row['hare_id'] == $row['hasher_id'] || $row['hare2_id'] == $row['hasher_id'] || $row['hare3_id'] == $row['hasher_id']) { $hare = '- hare'; } else { $hare = ''; } echo $row['hasher_name'] . ' <b>' . $hare . '</b>'; } } else if($_GET['submit_hasher']) { # if submit_hasher is present, pull up all of their hashes and aliases # select all the hashes that this person has attended $a_query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id && hr.hasher_id = " . $_GET['hasher_id'] . " ORDER BY h.hash_date DESC "; $a_result = mysql_query($a_query) or die('Error selecting the person\'s Hashes . '); $x = 1; while($a_row = mysql_fetch_array($a_result)) { if($x == 1) { echo '<strong>Hash Attendance Record For ' . $a_row['hasher_name'] . '</strong> <em>(' . mysql_num_rows($a_result) . ' total hashes)</em>'; $x++; } echo '#' . $a_row['hash_num'].' ' . $a_row['hash_name'] . ' on ' . date("D, d M Y", strtotime($a_row['hash_date'])); # see if this person was a hare if($a_row['hasher_id'] == $a_row['hare_id'] || $a_row['hasher_id'] == $a_row['hare2_id'] || $a_row['hasher_id'] == $a_row['hare3_id']) { echo ' - <b>hare</b>'; } echo ''; } echo ''; } echo ' <table width="100%"> <br /> <tbody> <tr> <br /> <td> '; ?> The problem is that everything that is returned from the WHILE loops is displayed in a single line. However, I want the data displayed with a line break between each result, like this: Header Return 1 from WHILE loop Return 2 from WHILE loop Return 3 from WHLIE loop How do I need to modify the code to make it display appropriately? Hi, I have some code which displays my blog post in a foreach loop, and I want to add some social sharing code(FB like button, share on Twitter etc.), but the problem is the way I have my code now, creates 3 instances of the sharing buttons, but if you like one post, all three are liked and any thing you do affects all of the blog post. How can I fix this? <?php include ("includes/includes.php"); $blogPosts = GetBlogPosts(); foreach ($blogPosts as $post) { echo "<div class='post'>"; echo "<h2>" . $post->title . "</h2>"; echo "<p class='postnote'>" . $post->post . "</p"; echo "<span class='footer'>Posted By: " . $post->author . "</span>"; echo "<span class='footer'>Posted On: " . $post->datePosted . "</span>"; echo "<span class='footer'>Tags: " . $post->tags . "</span>"; echo ' <div class="addthis_toolbox addthis_default_style "> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_counter addthis_pill_style"></a> </div> <script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script> <script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=webguync"></script>'; echo "</div>"; } ?> So I'm basically done an assignment, however I'm having the biggest brainfart at the moment. For the life of me I cannot remember how to "jump line" in a file and have to put "end" at the end of my txt files. Also I have to put a break in my code which messes up my formatting:
$coursedata = explode(' ', rtrim($coursedata)); $studentdata = explode(' ', rtrim($studentdata)); fwrite($fp, $number.'||'.$_POST['course'].' '.$content);Here is the main code below for the script: <html> <head> <?php $success = 0; $number_of_registered = 0; $course_array = getdatafile('courses.txt'); $registered_array = getdatafile('register.txt'); #______________global variables____________________ function getdatafile($file) { # code... $coursedata = file_get_contents($file); $coursedata = explode(' ', rtrim($coursedata)); unset($coursedata[count($coursedata) - 1]); $course_array = array(); foreach($coursedata as $row) { $course_array[] = explode('||', $row); } return $course_array; } #_____________functions_______________________ if (isset ($_POST['name']) and isset ($_POST['number']) and isset ($_POST['course'])) { #________________test if the post exists $name = $_POST['name']; $number = $_POST['number']; $found = 0; $findregistered = 0; for ($i = 0; $i < sizeof($registered_array); $i++) { if ($registered_array[$i][0] == $_POST['number'] && $registered_array[$i][1] == $_POST['course']) { # ___________test if the student is enrolled in this course $findregistered = 1; } if($registered_array[$i][1] == $_POST['course']) { #________counter of the number registered in this course $number_of_registered++; } } for ($i = 0; $i < sizeof($course_array); $i++) { if ($course_array[$i][1] == $_POST['course']) { # ______________this test if the number of registered is the max $course_name = $course_array[$i][0]; $findcourse = 1; if($number_of_registered < $course_array[$i][2]) { $number_max = 0; } else { $number_max = 1; } } } $studentdata = file_get_contents('students.txt'); $studentdata = explode(' ', rtrim($studentdata)); for ($i = 0; $i < sizeof($studentdata); $i++) { list($studentname, $studentnumber) = explode("||", rtrim($studentdata[$i])); if (strtoupper($name) == strtoupper($studentname) && strtoupper($number) == strtoupper($studentnumber)) { $found = 1; if ($findcourse == 1 && $findregistered == 0 && $number_max == 0) { # _____________________do all the tests to record the student in the course("register.txt") and do it if all the test are checked $success = 1; $content = file_get_contents('register.txt'); $fp = fopen('register.txt', 'w'); fwrite($fp, $number.'||'.$_POST['course'].' '.$content); fclose($fp); echo "<title>".strtoupper($name).",".strtoupper($studentname)."</title>"; } } } } ?> <style> body, p{padding: 0;margin: 0;} </style> </head> <body> <form action="index.php" method="POST"> <?php if (isset ($_POST['course'])) { $course = htmlentities ($_POST['course']); # ___________________print the information of rgester in the screen for if ($success == 1) { echo "You have successfully enrolled in $course_name, $course!"; } if($found == 0) { echo 'The credentials you have entered are incorrect, please try again.'; } else { if($findregistered == 1) { echo 'You have already enrolled in this course.'; } else { if($number_max == 1) { echo "Sorry $course_name, $course is full, please select another course."; } } } } ?> <p>Courses</p> <p><input name = "name" placeholder = "Student Name" type = "text"></p> <p><input name = "number" placeholder = "Student Number" type = "text"></p> <p><select name = "course" size = "1"> <option id = "select">-- Select Course --</option> <?php for ($i = 0; $i <sizeof($course_array); $i++) { $number_of_registered1 = 0; for ($j = 0; $j < sizeof($registered_array); $j++) { if($registered_array[$j][1] == $course_array[$i][1]) { $number_of_registered1++; } } $a = '<option value = "'.$course_array[$i][1].'">'.$course_array[$i][0].' registered:'.$number_of_registered1.'</option>'; echo $a; } ?> </select></p> <p><input type = "submit" value = "Send"><input type = "reset" value = "Clear"></p> </form> </body> </html>Attached Files courses.txt 94bytes 0 downloads register.txt 3bytes 0 downloads students.txt 103bytes 0 downloads index.php 4.19KB 0 downloads i am trying to pull a .txt file for a class assignment and it is pulling everything except for line 1 any suggestions would be great html: <html> <head> <title>Weekly Report</title> <link rel ="stylesheet" type="text/css" href="sample.css" /> </head> <body> <h1>Weekly Report</h1> <p> <form action = "weeklyReport1Boles.php" method = "post" > <p> <input type = "submit" value = "Display the Report" /> </p> </form> </body> </html> txt.file 1 236.00 2 284.00 3 148.00 4 128.00 5 0.00 6 110.00 7 0.00 8 php file: <?php $total = $_POST['total']; $avgDailyIncome = $_POST['avgDailyIncome']; $badDays = $_POST ['badDays']; $paintFile = $_POST ['paintfile']; $nextDay = $_POST['nextDay']; $paintFile = fopen("weeklyDataBoles.txt","r"); $week = fgets($paintFile); $total = 0; for ($count = 1; $count <=8; $count = $count +1) { $nextDay = fgets($paintFile); $total = $total + $nextDay; } $avgDailyIncome = $total/7; print("<p>TOTAL INCOME FROM PAINT CONTRACTS: "); print("$".number_format($total, 2)."</p>"); print("<p>AVG DAILY INCOME FROM PAINT CONTRACTS: "); print("$".number_format($avgDailyIncome, 2)."</p>"); print("<p>NUMBER OF DAYS with NO INCOME: $badDays.</p>"); ?> </body> </html> hi, im using the following code to read the content of a file, and then add a line to the end of the file. Code: [Select] $file = dirname(dirname(dirname(__FILE__))).'/includes/settings.php'; $read = fopen($file, 'r')or die('Opening Error'); $content = fread($read, filesize($file)); fclose($read)or die('Close Error'); if(isset($_POST['cat_bg'])) { $write = fopen($file, 'w')or die('Opening Error'); $cat_bg = $_POST['cat_bg']; $new_content = $content.'$color[\'cat_header\'][\'background\'] = '.$cat_bg.';'; fwrite($write, $new_content)or die('Write Error'); fclose($write); } however i would like to delete a line from the file before the content in inserted as the new line i am inserting is a duplicate variable with a different value. Can anyone help? Hello, I'm trying to read the first line of some large files by PHP, which means, the ideal solution does not work: Quote $content = file($file_import); $fields = explode(",", $content[0]); Quote Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 110 bytes) in C:\wamp\www\exchange\admin\import.php on line 55 Is there any other way to read only the first line without opening the whole file? Thanks!! Hi I need to read a file and if a line match then proceed, file have content like this file.txt Code: [Select] this is line one this line two and this line three my code: $content = file_get_contents("file.txt"); if (strstr("this line two", $content)) { echo 'matched'; } else { echo 'not matched'; } but this always give not matched. any help please Hello everybody! Keep in mind I'm new to PHP but get the basics I'm trying to collect email addresses from a web-form that gets filled out on a website into a simple txt file on the server. The problem is the emails get appended one right after the other with no spaces so it looks like "user@server.comuser2@server.comuser3@server.com" and so on. What I'm trying to do is either separate them by a comma, or put them on a new line but whatever I try, it will not accept it. Anyway, here is the code that I have: Code: [Select] $fp = fopen("/home/fullertr/public_html/email_collector.txt","a"); fwrite($fp,$_POST['visitormail' . "\n"]); fclose($fp); unset($_POST); Thanks for any help! Hi everyone. Well, i need help how to check a file line by line, (each line contains 1 ip address) and compare it with a variable. I have written some code but it doesn't work. Please help!! Code: [Select] $refile=''; while(!feof($file)) { $refile=fgets($file); if (strcmp($refile,"YES") == 0) echo $refile ."OK". "<br />"; else echo $refile . "NO OK ". "<br />"; } fclose($file); ?> |