PHP - Need Help Reading A .gz File Line By Line
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> Similar Tutorialsi 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. what 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 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: 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. 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! 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? 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 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 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. 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); ?> Hi guys. im using this line to log any users that log into my site. It writes to the log correctly however it doesn't leave a new a line. Can anyone see what ive done wrong with my code. thanks. Code: [Select] fwrite($fh, $_SESSION['username'] . ' at ' . strftime('%c') . "\n"); Hi to everyone. So, I have a little php code that reads line by line from a txt file, specifically i have 1 IP address for each line, and compares it with the current user's IP. It's like a little blacklist code. But it doesn't work. Can anyone see what i am doing wrong? Code: [Select] $file = fopen("ipblacklist.txt", "r") or exit("Unable to open file!"); //Output a line of the file until the end is reached $ipblacklist=''; $refile=''; while(!feof($file)) { if (fgets($file)== $_SERVER['REMOTE_ADDR']) $ipblacklist='error'; $refile=fgets($file); } fclose($file); Thank you in advance 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 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. 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’; }
|