PHP - How To Loop Line By Line.
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);
Similar Tutorialswhat im trying to do is take a youtube embed code find the URL code for that video and remove all other parts of the code keeping only the URL of the video after i get the URL by it self then replace the http://www.youtube.com/ part of the URL with http://i2.ytimg.com/vi/ to do this i know that i need something like this to get the URL of the video http://www.youtube.com/((?:v|cp)/[A-Za-z0-9\-_=]+) but how to only return just the URL is something idk how to do then use str_replace http://www.youtube.com/(?:v|cp)/" with http://i2.ytimg.com/vi/ so in the end im asking if anyone know how to remove all other codes i dont want and only keep the URL this may have to be done using "regex" im not sure as i dont know to much about regex and what it can do but does sound like it would help lol 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, 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 i have to read a single line from a csv, its a really big file and i only need one column.
i need the response to be a string ,i made a search and found the following code but i dont have any idea how to get a single line from a single string per run .
<?php $row = 1; //open the file if (($handle = fopen("file.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } ?> Edited by bores_escalovsk, 16 May 2014 - 06:38 PM. Hi. I want a simple textbox, that when submited, will replace very every new line, with the <br> tag. What will happen, when it submits, it will take the contents of a textbox, add the <br> tag where a new line is suposed to be, and save the string to a MySQL Database. I think this is the easiest way of allowing a user to edit what appears on a website when logged in, but if there is a easier way, then please tell me. What I am trying to do, is a login page, and once logged in, you enter new text into the textbox, click submit, and on the website homepage, the main text will change to what was submitted. But if there is a new line, I think the only way in HTML to make one is to put a <br> tag, so I want the PHP to but that tag wherever there is a new line. Sorry if I am confusing, I am not that advanced at PHP, but I would be very happy if you could supply me with the correct code. Time is running out... If you do not understand me, please tell me -- PHPLeader (not) Dear All Good Day, i am new to PHP (a beautiful server side scripting language). i want to send a mail with line by line message i tried with different types like by placing the things in table and using <br /> but the thing is the tags are also visible in the message of the mail. Here is my code: $message1 = "Name :". $_REQUEST['name']."<br />"; $message1 .= "Surname :". $_REQUEST['surname']."<br />"; $message1 .= "Cellphone :". $_REQUEST['mobileno']."<br />"; $message1 .= "Telephone :". $_REQUEST['landno']."<br />"; $message1 .= "Fax :". $_REQUEST['fax']."<br />"; $message1 .= "Company :". $_REQUEST['company']."<br />"; $message1 .= "Email :". $_REQUEST['email']."<br />"; $message1 .= "Country :". $_REQUEST['country']."<br />"; $message1 .= "Enquity :". $_REQUEST['enquiry']."<br />"; $message1 .= "Date&Time :". $date."<br />"; For this code if try to print/echo it it is working fine it is displaying line by line, but using this variable ($message1) in the mail these <br /> are also visible. Can any one guide me to resolve(to remove these tags from the message part) this issue. Thanks in Advance. :confused: 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. How to get this echo line to display as one line? No matter what I have done it displays as two lines. I even tried <nobr></nobr> Teachers Name: John Jones $userid = mysql_real_escape_string($_GET['user_id']); $sql = "select * from users where `id`='$userid' "; $rs = mysql_query($sql); while($row = mysql_fetch_array($rs)) { echo "<h3>Teachers Name: </h3>" . $row["first_name"] . " " . $row["last_name"] ; } Thanks for your help. 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 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 gday all! just starting to learn php but having a liitle problem with \n forcing a line break. in my situation it simply doesnt. looking at this what have i done wrong? Code: [Select] echo "<div class=\"imgcontainer\"><a href='$row[filename]' rel='shadowbox[thingo]'><img class= 'thumbnail' img src='$row[filename]'/></a><div class=\"thetext\">Artwork: $row[name]\nArtist:$row[artist]</div></div> "; Thanks <?php ob_start(); include "connect.php"; // Define $myusername and $mypassword $username=$_POST['username']; $password=$_POST['password']; // To protect MySQL injection (more detail about MySQL injection) $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM accounts WHERE username='$username' and password='$password'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1) { // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("username"); session_register("password"); echo "&msgText=Entrance Granted!\n"; } else { echo "&msgText=Invalid Login!\n"; } return false; ob_end_flush(); ?> this line right here what would the URL be to work correctly $sql="SELECT * FROM accounts WHERE username='$username' and password='$password'"; if this line means this $sql="SELECT * FROM accounts WHERE username='$username'"; http://wiistream.net/flash.login.php?username=Mytest = echo "&msgText=Entrance Granted!\n"; see i dont know is it http://wiistream.net/flash.login.php?username=Mytest&password=123456 I cant seem to login with a URL code because I dont know what it is? echo "<div id='wrap'><div id='header'>" . implode("</div>", array_keys($sports)) . ; I get the following error: Parse error: syntax error, unexpected ';' in /hermes/bosweb/xxxxx/xxx/xxxxxxxxxxxxxxxx/xxxxx/xxx_xxxx/xxx_xxxxxx.php on line 75 The above line is 75. I have changed the quotes using ' ' or " " and no matter what I do I continue to get errors.. where am I going wrong here? Thanks! Hi all, The code creates 4 select boxes.The user clicks on one item in each of the boxes and these are entered into the SQL statement.Trouble is I keep getting error after error all referring to line 59(the SQL statement line) can any keen eyed PHP freak see what I am doing wrong(or even if the whole of the code is any good)..Not too experienced with php so any comments suggestions(or laughs) greatly appreciated. <!DOCTYPE HTML> <html> <body> <select name = "author"> <option value="kendavies">ken davies</option> <option value="arthursmith">arthur smith</option> <option value="gillrafferty">gill rafferty</option> <option value="mollybrown">molly brown</option> <option value="gilbert riley">gilbert riley</option> <option value="colinwilson">colin wilson</option> <option value="jamesgreen">james green</option> <option value="arnoldlaing">arnold laing</option> <option value="cathyellis">cathy ellis</option> <option value="carolreed">carol reed</option> </select> <select name = "publisher"> <option value="yonkers">yonkers</option> <option value="blueparrot">blue parrot</option> <option value="zoot">zoot</option> </select> <select name = "yearpublished"> <option value="2003">2003</option> <option value="2004">2004</option> <option value="2005">2005</option> <option value="2006">2006</option> <option value="2007">2007</option> <option value="2008">2008</option> </select> <select name = "genre"> <option value="adventure">adventure</option> <option value="thriller">thriller</option> <option value="crime">crime</option> <option value="biography">biography</option> <option value="romance">romance</option> </select> $aa = "author" $bb = "publisher" $cc = "yearpublished" $dd = "genre" <?php $aa = "author"; $bb = "publisher"; $cc = "yearpublished"; $dd = "genre"; mysql_connect ("localhost","root","") or die(mysql_error()); mysql_select_db ("authors") or die(mysql_error()); $strSQL = SELECT * FROM `books` WHERE author = '".$aa."' AND publisher = '".$bb."' AND yearpublished = '".$cc."' AND genre ='".$dd."'" "; $rs = mysql_query($strSQL;); while($row = mysql_fetch_array($rs) ) { print $row ['ID']."<br/>"; print $row ['author']."<br/>"; print $row ['booktitle']."<br/>"; print $row ['publisher']."<br/>"; print $row ['yearpublished']."<br/>"; print $row ['genre']."<br/>"; print $row ['copiessold']."<br/>"; } mysql_close(); ?> </body> </html> I am sorry even i didn't say hello to forum but i need this snippet very urgently. i have Zero knowledge of PHP but unfortunately i need a small code as follow. ok... so my page.php works perfectly when it is receiving date ie the url is page.php?id=x, but how do i set a default for the page? for example if someone browses to page.php at the moment i just get an error message: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" shouldnt it echo Result not found? what have i done wrong?? php below: <?php $max_columns = 3; include_once "include/globals.php"; //globals contains db connection if (isset($_GET['cat-id'])) { $id = $_GET['cat-id']; } ?> <?php //Get database Results $result = mysql_query("SELECT * FROM Products WHERE is_active = 1 AND catagory_id = $id ") or die(mysql_error()); if(mysql_num_rows($result)===0) { $output = "No records found.\n"; } else { $output = "<table>\n"; //keeps getting the next row until no more records $recNo = 0; while($row = mysql_fetch_array($result)) { $recNo++; //Start new row when needed if($recNo%$max_columns==1) { $output .= "<tr>\n"; } //Create TD for record $output .= "<td><div class=\"table-bg\">"; $output .= "<div class=\"title\">{$row['Name']}</div>"; $output .= "<div class=\"image\">"; $output .= "<a href=\"product_detail.php?id=\"><img src=\"{$row['image']}\" width=\"100\" alt=\"\" border=\"0\"></a>"; $output .= "</div>"; $output .= "<div class=\"tag_line\">{$row['Tag_Line']}</div>"; $output .= "<div class=\"price\">Now Only: £{$row['Website_Price']}</div>"; $output .= "<div class=\"prod-footer\"><a href=\"product_detail.php?id={$row['ID']}\">more info</a></div>"; $output .= "</div></td>\n"; //Close row when needed if($recNo%$max_columns==0) { $output .= "</tr>\n"; } } //Close final row if needed if($recNo%$max_columns!=0) { $output .= "</tr>\n"; } $output .= "<table>\n"; } ?> <!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=utf-8" /> <title>Untitled Document</title> <link href="styles/stylesheet.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="Wrapper"> <?php include "include/header.php"; ?> <?php include "include/thinnav.php"; ?> <?php include "include/nav.php"; ?> <div id="main"> <?php //echo $output; ?> </div> <?php include "include/right-nav.php"; ?> <?php include "include/footer.php"; ?> </div> </body> </html> pleasse help this is doing my nuts in........... I'm trying to insert the contents of a textarea into a MySQL database but I am wondering what the best way is to preserve the users line breaks. I know that you can use nl2br() to convert "\n" into "<br />" when the retrieve data from the database but I am looking at a way to insert these line breaks when I enter the data. Thanks for any help. I've looked it, and I guess it's right in front of me but I don't see it. Parse error: syntax error, unexpected T_STRING, expecting ']' in /home/a8079066/public_html/view.php on line 24 echo "<b>Name:</b> ". $query['name'] ."<br/><b>Description:</b> ". $query['description'] ."<hr><a href='/mods/". $query['id'] .".zip'><h2>[DOWNLOAD]</h2></a><hr>"; Hi.. I have a php file where i have only one line which says header('Location: index.php'); How do i run this php file in the terminal on fedora 14? Thanks, Rohit |